日期:2014-05-20 浏览次数:20692 次
package test.bwl; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class SocketClient { public static void main(String[] args) { Socket socket = null; DataOutputStream doc; DataInputStream in ; try { socket = new Socket("127.0.0.1", 1234); OutputStream netOut = socket.getOutputStream(); doc = new DataOutputStream(netOut); in = new DataInputStream(socket.getInputStream()); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int flag=1; doc = new DataOutputStream(netOut); in = new DataInputStream(socket.getInputStream()); while(flag==1) { System.out.print("请输入要发送的内容(输入exit退出)\n"); String what=br.readLine(); if("exit".equals(what)) break; doc.writeUTF(what); String res = in.readUTF(); System.out.println("客户端--->"+res); } doc.close(); in.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (socket != null) { try { socket.close(); System.out.println("关闭成功"); } catch (IOException e) { } } } } }
package test.bwl; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class SocketManager { /** * @param args * @throws IOException */ public static void main(String[] args) { SocketManager manager = new SocketManager(); System.out.println("启动监听....."); manager.doListen(); } public void doListen() { ServerSocket server; try { server = new ServerSocket(1234); while (true) { Socket client = server.accept(); new Thread(new SSocket(client)).start(); } } catch (IOException e) { e.printStackTrace(); } } //服务器进程 class SSocket implements Runnable { Socket client; public SSocket(Socket client) { this.client = client; } public void run() { DataInputStream input; DataOutputStream output; try { input = new DataInputStream(client.getInputStream()); output = new DataOutputStream(client.getOutputStream()); String listMsg = input.readUTF(); output.writeUTF("服务器接收-->发回: " + listMsg ); System.out.println("接收: " + listMsg); } catch (Exception e) { e.printStackTrace(); } } } }