http://blog.csdn.net/defonds/article/details/7971259
多个客户端对应一个服务端的通信的一个小例子。
服务端和客户端代码:
public class Server { /** * 监听的端口 */ public static final int PORT = 12345; public static void main(String[] args) { System.out.println("服务器启动》》》》》》"); Server server = new Server(); server.init(); } public void init(){ try { ServerSocket serverSocket = new ServerSocket(PORT); while (true){ //一旦有堵塞,表示服务器与客户端获得了连接 Socket client = serverSocket.accept(); new HandlerThread(client); } } catch (Exception e) { e.printStackTrace(); } } private class HandlerThread implements Runnable{ private Socket socket; public HandlerThread(Socket socket) { this.socket = socket; new Thread(this).start(); } @Override public void run() { try { //读取客户端数据 DataInputStream input = new DataInputStream(socket.getInputStream()); //这里要注意和客户端输出流的写方法对应,否则会抛 EOFException String clientInputStr = input.readUTF(); //处理客户端发送的数据 System.out.println("客户端发过来的内容:"+clientInputStr); //想客户端发送消息 DataOutputStream out = new DataOutputStream(socket.getOutputStream()); System.out.println("请输入: "); String outStr = new BufferedReader(new InputStreamReader(System.in)).readLine(); out.writeUTF(outStr); out.close(); input.close(); } catch (IOException e) { System.out.println("服务器异常:"+e.getMessage()); }finally { if (socket != null) { try { socket.close(); } catch (Exception e) { socket = null; System.out.println("服务端 finally 异常:" + e.getMessage()); } } } } } }
public class Client { public static final int PORT = 12345; public static final String IP_ADDR = "localhost"; public static void main(String[] args) { System.out.println("客户端启用》》》》》》"); System.out.println("当接收到服务器端字符为 "OK" 的时候, 客户端将终止 "); while (true){ Socket socket = null; try { //创建一个流套接字并将其连接到指定主机上的指定端口号 socket = new Socket(IP_ADDR,PORT); socket.setSoTimeout(5000); //读取服务器端数据 DataInputStream input = new DataInputStream(socket.getInputStream()); //向服务器端发送数据 DataOutputStream out = new DataOutputStream(socket.getOutputStream()); System.out.print("请输入: "); String str = new BufferedReader(new InputStreamReader(System.in)).readLine(); out.writeUTF(str); String ret = input.readUTF(); System.out.println("服务器端返回过来的是: " + ret); if (ret.endsWith("OK")) { System.out.println("客户端将关闭连接"); Thread.sleep(500); break; } out.close(); input.close(); } catch (IOException | InterruptedException e) { e.printStackTrace(); }finally { if (socket != null) { try { socket.close(); } catch (IOException e) { socket = null; System.out.println("客户端 finally 异常:" + e.getMessage()); } } } } } }