简体   繁体   English

TCP线程服务器/客户端

[英]TCP threaded server/client

I'm trying to make a threaded TCP server that accept multiple client.我正在尝试制作一个接受多个客户端的线程 TCP 服务器。 It's only accepting one client.它只接受一位客户。 Any idea on how to make the server accepting multiple client?关于如何让服务器接受多个客户端的任何想法?

Here is what I tried so far:这是我到目前为止尝试过的:

I changed the server code.我更改了服务器代码。 I ran both the server and the client, but it seems that it's only one thread is working.我同时运行了服务器和客户端,但似乎只有一个线程在工作。 Should I change the ports or something?我应该更改端口还是什么?

Server code:服务器代码:

package tcpecho;

import java.io.*; 
import java.net.*;


class TCPserver  implements Runnable {
private static String clientMSG;
private static String serverRespond;
private static ServerSocket MySocket=null;
private static Socket client;
private static Socket connectionSocket = null;
private BufferedReader inFromClient = null;
public TCPserver(Socket client){
    TCPserver.client=client;}

public static void main(String[] args)  {

    try {
        MySocket  = new ServerSocket(6880);
        System.out.println("TCP server is listining");
    } catch (IOException e) {

    System.err.println("TCP server is not listining :   "+MySocket.getLocalPort());
    } 

    try {
        connectionSocket = MySocket.accept();
        (new Thread(new TCPserver(connectionSocket))).start();

        System.out.println("Is connected now : "+connectionSocket.getInetAddress());

    } catch (IOException e) {

        System.err.print("Accept failed");
    }
}



public void socketProcess( )
{

    try {
        inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
    } catch (IOException e) {
        System.err.println("Message from client is not reachable");
    }

    DataOutputStream outToClient = null;
    try {
        outToClient = new DataOutputStream(connectionSocket.getOutputStream());
    } catch (IOException e) {
        System.err.println("Message to client is not reachable");

    }

    try {
        clientMSG = inFromClient.readLine();
    } catch (IOException e) {
        System.err.println("Message from client is not readable");
    }

    serverRespond = clientMSG +connectionSocket.getInetAddress()+ '\n';

    try {
        outToClient.writeBytes(serverRespond);
    } catch (IOException e) {
        System.err.println("Message to client is not out");
    } 

    try {
        MySocket.close();
    } catch (IOException e1) {

        System.err.println("Unable to close the socket");
    }

}



@Override
public void run() {
    socketProcess();

} 

} }

And here is my Client code:这是我的客户端代码:

package task3;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

class Client {
    public static void main(String argv[]) throws Exception {

        String str;
        String strFromServer;
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

        Socket client = null;
        // for(int i=0;i<10;i++){
        int port = 6880;
        try {
            client = new Socket("192.168.56.1", port);
        } catch (Exception e) {
            System.err.println("Couldn't connect to the port" + port);
            System.exit(1);
        }

        DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());

        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
        System.out.println("Write a message to the server :");
        str = inFromUser.readLine();

        outToServer.writeBytes(str + '\n');
        strFromServer = inFromServer.readLine();
        System.out.println("Respond from server: " + strFromServer);
        client.close();
    }
}

Right after you do this在你这样做之后

connectionSocket = MySocket.accept();

you need to pass this connectionSocket instance to a new Thread and call start on that Thread.您需要将此connectionSocket实例传递给一个新线程并在该线程上调用start

Also, move all the connectionSocket processing logic to your Thread class's run method此外,将所有connectionSocket处理逻辑移至 Thread 类的run方法
(this logic is currently in the main method after this line mentioned above). (这个逻辑目前在上面提到的这一行之后的main方法中)。

For implementing your own Thread , you can either extend Thread or implement Runnable .为了实现您自己的Thread ,您可以扩展Thread或实现Runnable

Check this link for some more details: Java Threads检查此链接以获取更多详细信息: Java 线程

Just a suggestion, If you are going to have multiple threads always opened to all your clients, you may want to check out the java.nio package which uses non blocking io.只是一个建议,如果您要始终向所有客户端打开多个线程,您可能需要查看使用非阻塞 io 的java.nio包。

This will allow you to handle many more connections.这将允许您处理更多的连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM