转自:http://developer.51cto.com/art/201202/317543.htm
现在做Java直接使用Socket的情况是越来越少,因为有很多的选择可选,比如说可以用spring,其中就可以支持很多种远程连接的操作,另外jboss的remoting也是不错的选择,还有Apache的Mina等等,但是在有些时候一些特殊情况仍然逃脱不了直接写Socket的情况,比如公司内部一些莫名其妙的游戏规则。
废话不说了,下面就看看如果自己写Socket应该怎么做吧。
首先是写一个Server类,这个类用来监听10000端口,并从这个端口接收消息然后输出,当收到“bye”时退出。
1 package com.googlecode.garbagecan.test.socket.sample1; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.io.PrintWriter; 7 import java.net.ServerSocket; 8 import java.net.Socket; 9 10 public class MyServer { 11 public static void main(String[] args) throws IOException { 12 ServerSocket server = new ServerSocket(10000); 13 Socket socket = server.accept(); 14 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 15 PrintWriter out = new PrintWriter(socket.getOutputStream()); 16 17 while (true) { 18 String msg = in.readLine(); 19 System.out.println(msg); 20 out.println("Server received " + msg); 21 out.flush(); 22 if (msg.equals("bye")) { 23 break; 24 } 25 } 26 socket.close(); 27 } 28 }
然后是一个Client类,这个类连接上面启动的Server类,然后接收任何用户输入,当遇到回车时发送字符串到Server上,当输入“bye”是退出。
1 package com.googlecode.garbagecan.test.socket.sample1; 2 3 import java.io.BufferedReader; 4 import java.io.InputStreamReader; 5 import java.io.PrintWriter; 6 import java.net.Socket; 7 8 public class MyClient { 9 public static void main(String[] args) throws Exception { 10 Socket socket = new Socket("localhost", 10000); 11 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 12 PrintWriter out = new PrintWriter(socket.getOutputStream()); 13 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 14 15 while (true) { 16 String msg = reader.readLine(); 17 out.println(msg); 18 out.flush(); 19 if (msg.equals("bye")) { 20 break; 21 } 22 System.out.println(in.readLine()); 23 } 24 socket.close(); 25 } 26 }
最后,首先运行MyServer类,然后MyClient类,然后在MyClient的控制台输入任意字符,可以看到当输入bye是server和client都会退出。