1.Socket-简单示例
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; /** * @name SocketServer端 * @author wujianxiong * @date 2016-5-16 */ public class EchoServer { private int port=8000; private ServerSocket serverSocket; public EchoServer() throws IOException{ this.serverSocket = new ServerSocket(port); System.out.println("服务器启动(端口:"+port+")"); } public EchoServer(ServerSocket serverSocket) { this.serverSocket = serverSocket; } public void service(){ while(true){ Socket socket = null; try { //服务器等待客户端连接 socket = serverSocket.accept(); System.out.println("客户端"+socket.getInetAddress()+":"+socket.getPort()+"已连接!"); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); String msg = null; while((msg=reader.readLine())!=null){ writer.println("echo:"+msg); if(msg.equals("bye")) break; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { if(socket!=null){ socket.close(); System.out.println("断开连接!"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //启动服务 public static void main(String[] args) throws IOException{ EchoServer echoServer = new EchoServer(); echoServer.service(); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; /** * @name Socket客户端 * @author wujianxiong * @date 2016-5-16 */ public class EchoClient { private String host = "localhost"; private int port = 8000; private Socket socket; public EchoClient() throws UnknownHostException, IOException { socket = new Socket(host, port); } private void talk() throws IOException{ BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in)); String msg = null; while((msg=localReader.readLine())!=null){ writer.println(msg); System.out.println(reader.readLine()); if(msg.equals("bye")) break; } socket.close(); } //访问服务 public static void main(String[] args) throws IOException { // TODO Auto-generated method stub EchoClient client = new EchoClient(); client.talk(); } }