编辑代码,使其能够接受许多客户端加入服务器?

Posted

技术标签:

【中文标题】编辑代码,使其能够接受许多客户端加入服务器?【英文标题】:Editing code, so it could be able to accept many clients joining on the server? 【发布时间】:2019-09-01 02:44:25 【问题描述】:

我想编辑此代码,以便它可以在我的服务器上接受更多客户端加入。该服务器仅用于接受一个客户端的连接,它可以发送和接收消息。但我想让它成为“多人”服务器。许多客户端连接到一台服务器。这是服务器端代码和客户端代码:

非常感谢您的帮助!

我的服务器代码:

import java.net.*;
import java.lang.*;
public class RecordAppServer 
    public static void main(String[] args) throws IOException 
        final int port = 8136;
        System.out.println("Server waiting for connection on port "+port);
        ServerSocket ss = new ServerSocket(port);
        Socket clientSocket = ss.accept();
        System.out.println("Recieved connection from "+clientSocket.getInetAddress()+" on port "+clientSocket.getPort());
        //create two threads to send and recieve from client
        RecieveFromClientThread recieve = new RecieveFromClientThread(clientSocket);
        Thread thread = new Thread(recieve);
        thread.start();
        SendToClientThread send = new SendToClientThread(clientSocket);
        Thread thread2 = new Thread(send);
        thread2.start();
    
class RecieveFromClientThread implements Runnable

    Socket clientSocket=null;
    BufferedReader brBufferedReader = null;

    public RecieveFromClientThread(Socket clientSocket)
    
        this.clientSocket = clientSocket;
    //end constructor
    public void run() 
        try
        brBufferedReader = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));       

        String messageString;
        while(true)
        while((messageString = brBufferedReader.readLine())!= null)//assign message from client to messageString
            if(messageString.equals("EXIT"))
            
                break;//break to close socket if EXIT
            
            System.out.println("From Client: " + messageString);//print the message from client
            //System.out.println("Please enter something to send back to client..");
        
        this.clientSocket.close();
        System.exit(0);
    

    
    catch(Exception ex)System.out.println(ex.getMessage());
    
//end class RecieveFromClientThread
class SendToClientThread implements Runnable

    PrintWriter pwPrintWriter;
    Socket clientSock = null;

    public SendToClientThread(Socket clientSock)
    
        this.clientSock = clientSock;
    
    public void run() 
        try
        pwPrintWriter =new PrintWriter(new OutputStreamWriter(this.clientSock.getOutputStream()));//get outputstream

        while(true)
        
            String msgToClientString = null;
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));//get userinput

            msgToClientString = input.readLine();//get message to send to client

            pwPrintWriter.println(msgToClientString);//send message to client with PrintWriter
            pwPrintWriter.flush();//flush the PrintWriter
            //System.out.println("Please enter something to send back to client..");
        //end while
        
        catch(Exception ex)System.out.println(ex.getMessage());
    //end run
//end class SendToClientThread

我的客户代码:

import java.io.*;
import java.net.*;
public class RecordAppClient 
    public static void main(String[] args)
    
        try 
            Socket sock = new Socket("192.168.0.2",8136);
            SendThread sendThread = new SendThread(sock);
            Thread thread = new Thread(sendThread);thread.start();
            RecieveThread recieveThread = new RecieveThread(sock);
            Thread thread2 =new Thread(recieveThread);thread2.start();
         catch (Exception e) System.out.println(e.getMessage()); 
    

class RecieveThread implements Runnable

    Socket sock=null;
    BufferedReader recieve=null;

    public RecieveThread(Socket sock) 
        this.sock = sock;
    //end constructor
    public void run() 
        try
        recieve = new BufferedReader(new InputStreamReader(this.sock.getInputStream()));//get inputstream
        String msgRecieved = null;
        while((msgRecieved = recieve.readLine())!= null)
        
            System.out.println("From Server: " + msgRecieved);
            //System.out.println("Please enter something to send to server..");
        
        catch(Exception e)System.out.println(e.getMessage());
    //end run
//end class recievethread
class SendThread implements Runnable

    Socket sock=null;
    PrintWriter print=null;
    BufferedReader brinput=null;

    public SendThread(Socket sock)
    
        this.sock = sock;
    //end constructor
    public void run()
        try
        if(sock.isConnected())
        
            System.out.println("Client connected to "+sock.getInetAddress() + " on port "+sock.getPort());
            this.print = new PrintWriter(sock.getOutputStream(), true); 
        while(true)
            //System.out.println("Type your message to send to server..type 'EXIT' to exit");
            brinput = new BufferedReader(new InputStreamReader(System.in));
            String msgtoServerString=null;
            msgtoServerString = brinput.readLine();
            this.print.println(msgtoServerString);
            this.print.flush();

            if(msgtoServerString.equals("EXIT"))
            break;
            //end while
        sock.close();catch(Exception e)System.out.println(e.getMessage());
    //end run method
//end class

【问题讨论】:

最好向我们展示您到目前为止所做的工作,以便我们检查您遇到问题的地方。 【参考方案1】:

您需要实现一个多线程服务器。

一般结构如下:

while(true) 
    1) Wait for client requests (Socket client = server.accept();)
    2) Create a thread with the client socket as parameter
        a) The new thread creates I/O streams (just like youre doing 
        with the PrintWriter and BufferedReader objects)
        b) Communicate with client (in your example - 
        brBufferedReader.readLine())
    3) Remove thread once the service is provided.

我建议您看一下 Oracle 文档: https://www.oracle.com/technetwork/java/socket-140484.html#multi

这也可能有用:http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html

【讨论】:

以上是关于编辑代码,使其能够接受许多客户端加入服务器?的主要内容,如果未能解决你的问题,请参考以下文章

tcp服务器和客户端交互

当必须接受许多连接时,我在客户端/服务器类型应用程序中遇到 Java 套接字问题

使用 gen_tcp 时的套接字接受率

使用Apache搭建一个个人静态网站

W-5-2 计算机加入域

Erlang TCP 服务器总是在接受时关闭