码迷,mamicode.com
首页 > 其他好文 > 详细

TCP数据交互

时间:2017-06-25 18:38:11      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:private   add   服务器   连接   logs   accept   first   pre   ddr   

服务器端:

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数据交互

标签:private   add   服务器   连接   logs   accept   first   pre   ddr   

原文地址:http://www.cnblogs.com/by-1642146903/p/7077331.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!