对java的socket一直很陌生,陌生到别人问我线程通信时,感觉自己无地自容,愧对自己多java的热爱。
正好最近项目抽风中,看到csdn上有相关资料,就自己写了点demo。希望对刚入门或则尽快掌握socket通信开发
的朋友有所启发。
服务端代码
1 /** 2 * @author draem0507@gmail.com 3 * @TODO java线程开发之一 单线程 4 * @version 1.0 5 * @date 2013-5-7下午09:19:45 6 * @blgos myblog:http://www.cnblogs.com/draem0507 7 */ 8 9 public class ServerTest { 10 11 public static void main(String[] args) throws IOException { 12 13 ServerSocket server = new ServerSocket(10000); 14 Socket socket = server.accept(); 15 BufferedReader in = new BufferedReader(new InputStreamReader(socket 16 .getInputStream())); 17 PrintWriter out = new PrintWriter(socket.getOutputStream()); 18 while (true) { 19 String msg = in.readLine(); 20 System.out.println("服务端收到的信息:" + msg); 21 out.println("server receive:" + msg); 22 out.flush(); 23 if (msg.equals("bye")) { 24 break; 25 } 26 27 } 28 29 socket.close(); 30 31 } 32 33 }
客户端代码
1 public class ClientTest { 2 public static void main(String[] args) throws Exception { 3 Socket socket = new Socket("localhost", 10000); 4 BufferedReader in = new BufferedReader(new InputStreamReader(socket 5 .getInputStream())); 6 PrintWriter out = new PrintWriter(socket.getOutputStream()); 7 BufferedReader reader = new BufferedReader(new InputStreamReader( 8 System.in)); 9 10 while (true) { 11 String msg = reader.readLine(); 12 out.println(msg); 13 out.flush(); 14 if (msg.equals("bye")) { 15 break; 16 } 17 System.out.println(in.readLine()); 18 } 19 socket.close(); 20 } 21 }
测试代码的时候,先运行服务端,在运行客户端。
因为是单线程的,所以没有办法多次运行客户端代码。如果要实现1-n模式,则需要用到多线程模式。