TCP数据交互
服务器端:
public class Server { private static ServerSocket server=null; private static PrintWriter out=null; private static BufferedReader reader=null; private static Map<String,Socket> userMessages=new Hashtable<String, Socket>(); private static void first(){ try { //服务器启动 server=new ServerSocket(1888); while(true){ //有客户连接时 Socket client=server.accept(); //保存客户端信息,ip、socket userMessages.put(client.getInetAddress().getHostAddress(), client); //开辟线程处理数据 new Thread(new Runnable() { @Override public void run() { try { //取得输出流 out=new PrintWriter(client.getOutputStream(),true); //取得输入流 reader=new BufferedReader(new InputStreamReader(client.getInputStream(),"utf-8")); out.println("欢迎登陆"); String message=reader.readLine(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } } catch (IOException e) { e.printStackTrace(); }finally{ if(server!=null){ try { server.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) { first(); } }
客户端:
public class Client { private static Socket client = null; private static PrintWriter out = null; private static BufferedReader reader = null; public static void main(String[] args) { try { client=new Socket("192.168.1.102",1888); out=new PrintWriter(client.getOutputStream().true); reader=new BufferedReader(new InputStreamReader(client.getInputStream())); //向服务器发送信息 out.println(""); //服务器发送过来的数据保存到变量 String message=reader.readLine(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }