zoukankan      html  css  js  c++  java
  • Socket通信和多线程的总结

    1.ServerSocket进行多线程接收

    package com.yh.chat;
    
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class ChatServerSocket {
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ServerSocket serversocket = null;
            Socket socket = null;
            try {
                serversocket = new ServerSocket(5005);
                while (true) {
                    socket = serversocket.accept();
                    ChatAcceptSocket accept = new ChatAcceptSocket(socket);
                    accept.start();
                }
                // 发送信息
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    package com.yh.chat;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.Socket;
    
    public class ChatAcceptSocket extends Thread {
        private Socket socket;
        
        public ChatAcceptSocket(){}
        public ChatAcceptSocket(Socket socket){
            this.socket=socket;
        }
        @Override
        public void run() {
            // TODO Auto-generated method stub
            InputStream is = null;
            BufferedReader br = null;
            // 接收信息
            try {
                is = socket.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String info = "";
                while ((info = br.readLine()) != null) {
                    OutputStream os = socket.getOutputStream();
                    byte[] replys = info.getBytes();
                    System.out.println("广播:"+info);
                    os.write(replys);
                    os.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }

    2.客户端进行连接(代码省略,参考:流式套接字:基于TCP协议的Socket网络编程(案例1)

    这里ServerSocket进行的广播仅限当前线程的中的socket,不会给其他线程的socket发送数据。

  • 相关阅读:
    9 与python2交互
    8 内置函数(未完成)
    7 事务
    [转]jquery.vTicker(垂直滚动)
    2015年工作总结(2016-02-02)
    jQuery plugin : jqTransform
    JQuery知识总结
    JQuery事件处理的注意事项
    JQuery基本选择器
    [二]JQueryMobile常用的组件介绍
  • 原文地址:https://www.cnblogs.com/YeHuan/p/11461190.html
Copyright © 2011-2022 走看看