欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java多线程tcp_TCP多线程(线程池)

程序员文章站 2022-06-05 23:51:05
...
package Threed;
/**
 * Created by SuPhoebe on 2015/12/27.
 * 基于TCP协议的Socket通信,实现用户登陆
 * 服务器端
 */

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class Server {
    private static ExecutorService executor = Executors.newFixedThreadPool(15);
    public static void main(String[] args) {
        try {
            //1.创建一个服务器端Socket,即ServerSocket,指定绑定的端口,并监听此端口
            ServerSocket serverSocket=new ServerSocket(8520);
            Socket socket=null;
            while(true){
                Thread thread = new Thread(new ServerThread(socket));
                //调用accept()方法开始监听,等待客户端的连接
                socket=serverSocket.accept();
                executor.execute(new ServerThread(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//     void TcpServer(){
//
//    }
}

上面是服务端

下面是多线程

package Threed;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerThread implements Runnable{

    Socket socket = null;//和本线程相关的Socket

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        OutputStream os = null;
        PrintWriter pw = null;

        try {
          is= socket.getInputStream();

            while (true) {
                byte[] bytes = new byte[1024];
                int len = is.read(bytes);
                System.out.println(new String(bytes,0,len));
            }
            //获取输出流,响应客户端的请求

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源即相关socket
            try {
                if(pw!=null)
                    pw.close();
                if(os!=null)
                    os.close();
                if(br!=null)
                    br.close();
                if(isr!=null)
                    isr.close();
                if(is!=null)
                    is.close();
                if(socket!=null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

}

客户端我用的是TCP&UDP测试工具。