TCP数据交互
Posted 莫轩ASL
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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(); } } }
以上是关于TCP数据交互的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 xcode 将快照划分为多个片段,以便让用户与每个片段进行交互?