server + client by socket

本文提供了一个Java Socket编程的基础示例,包括客户端和服务端的实现方式。服务端监听特定端口接收客户端消息并打印,客户端连接到服务端并发送输入的消息。
Java 的通信编程,编程题(或问答),用 JAVA SOCKET 编程, 读服务器几个字符,再写入本地显示?

Server端
public class Server {
public static void main (String [] args){
new Server();
}
public Server(){
ServerSocket ss = null ;
Socket soc;
BufferedReader in = null;
try {
ss=new ServerSocket(12345);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(true)
try {
soc = ss.accept();
System.out.println("有人进来了 ip为:"+soc.getInetAddress().getHostAddress()+" : "+soc.getPort());
in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
System.out.println("Client send is "+in.readLine());
} catch (IOException e) {
if(ss!=null){
try {
System.out.println("服务端错误处理");
ss.close();
} catch (IOException e2) {
}
}
// TODO Auto-generated catch block
System.out.print("错误是"+e.getLocalizedMessage());
e.printStackTrace();
}
}
}


Client端
public class Client {
Socket socket;
public static void main(String[] args) {
// TODO Auto-generated method stub
new Client();
}
public Client(){
PrintWriter out = null;
BufferedReader in =null;
try {
socket = new Socket("127.0.0.1",12345);
System.out.println("Server Connect Success");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(true){
try {
System.out.println("打字:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(socket.getOutputStream(),true);
out.println(br.readLine());
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("client in :" + in.readLine());
} catch (Exception e) {
try {
System.out.println("Client is wrong");
socket.close();
out.close();
in.close();
} catch (Exception e1e) {
}
}
}
}
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值