Server 端:
package foundation; import java.io.*; import java.net.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class SimpleSocketServer { public static void main(String[] args) { // TODO Auto-generated method stub ServerSocket serverSocket = null; /* * Socket socket = null; OutputStream os = null; InputStream is = null; */ // 监听端口号 // Socket socket = null; /* OutputStream os = null; InputStream is = null;*/ int port = 10001; try { // 建立连接 serverSocket = new ServerSocket(port); // 获得连接 while (true) { // socket = ExecutorService es = Executors.newCachedThreadPool(); es.execute(new businessTask(serverSocket.accept())); } // 接收客户端发送内容 } catch (Exception e) { e.printStackTrace(); } finally { try { // 关闭流和连接 /* os.close(); is.close();*/ // socket.close(); serverSocket.close(); } catch (Exception e) { } } } } class businessTask implements Runnable { private Socket socket; private OutputStream os; private InputStream is; public businessTask(Socket socket) { this.socket = socket; } // 监听端口号 int port = 10001; @Override public void run() { // TODO Auto-generated method stub try { is = socket.getInputStream(); byte[] b = new byte[1024]; int n = is.read(b); // 输出 System.out.println("客户端发送内容为:" + new String(b, 0, n)); // 向客户端发送反馈内容 os = socket.getOutputStream(); os.write(b, 0, n); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
client端:
package foundation; import java.io.*; import java.net.Socket; import java.net.UnknownHostException; public class SimpleSocketClient { public static void main(String[] args) { // TODO Auto-generated method stub Socket socket=null; InputStream is=null; OutputStream os=null; String serverIP="127.0.0.1"; int port=10001; String data="hello"; try { socket=new Socket(serverIP,port); os=socket.getOutputStream(); os.write(data.getBytes()); is=socket.getInputStream(); byte[] b=new byte[1024]; int n=is.read(b); System.out.println("server response:"+new String(b,0,n)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { os.close(); is.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
原文地址:http://www.cnblogs.com/ericmeng/p/3858423.html