简体   繁体   English

具有多个客户端的Java Socket编程

[英]Java Socket programming with more than one client

I have code which works with one client connection. 我有适用于一个客户端连接的代码。 What I need is ability for the server to handle multiple client requests using multithreaded approach. 我需要的是服务器能够使用多线程方法处理多个客户端请求的功能。

I found some solutions, but it's not meet my requirements, like this , or this 我找到了一些解决方案,但是不符合我的要求,例如thisthis

Server.java 服务器.java

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends User {
    private Socket clientSocket;
    private ServerSocket serverSocket;


    public Server() {
        super();
    }

    private void createConnection() {
        try {
            InetAddress locIP = InetAddress.getByName("127.0.0.1");
            serverSocket = new ServerSocket(9999, 0, locIP);


            //      serverSocket = new ServerSocket(4444, 4444, InetAddress.getByName("192.168.0.101"));
        } catch (IOException e) {
            System.err.println("Could not listen on port: 9999 ." + e);
            System.exit(1);
        }
    }

    private void closeConnection() {
        try {
            serverSocket.close();
        } catch (IOException e) {
            System.err.println(e);
        }
    }

    @Override
    public void connect() {
        createConnection();

        //Socket clientSocket=null;
        try {
            clientSocket = serverSocket.accept();

            System.out.println("Client connected! "
                    + "IP: "
                    + clientSocket.getInetAddress()
                    + ", port: "
                    + clientSocket.getPort());


        } catch (IOException e) {
            System.err.println("Accept failed. " + e);
            System.exit(1);
        }
    }


    @Override
    public void disconnect() {
        try {
            clientSocket.close();
        } catch (IOException e) {
            System.err.println(e);
        }

        closeConnection();
    }


    @Override
    public Socket getSocket() {
        return clientSocket;
    }

    @Override
    public String toString() {
        return new String("Server");
    }

}

Client.java 客户端.java

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client extends User {

    private Socket socket;


    public Client() {
        super();
    }

    @Override
    public Socket getSocket() {
        return socket;
    }

    @Override
    public void connect() {
        try {
            InetAddress locIP = InetAddress.getByName("127.0.0.1");
          //  socket = new Socket(9999, 0, locIP);
          //  socket = new Socket("localhost", 9999);       oryginalny
              socket = new Socket(locIP, 9999);

        } catch (UnknownHostException e) {
            System.err.println("The host not found! " + e);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Can't find connection! " + e);
            System.exit(1);
        }
    }


    @Override
    public void disconnect() {
        try {
            socket.close();
        } catch (IOException e) {
            System.err.println(e);
        }
    }

    @Override
    public String toString() {
        return new String("Client");
    }
}

SendButton.java SendButton.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintStream;


import javax.swing.JButton;
import javax.swing.JTextPane;


@SuppressWarnings("serial")
public class SendButton extends JButton {
    private JTextPane incomingMessages;
    private JTextPane messageToSend;
    private User user;

    public SendButton(User user, JTextPane incomingMessages, JTextPane messageToSend) {
        super("Send!");
        this.user = user;
        this.incomingMessages = incomingMessages;
        this.messageToSend = messageToSend;

        this.addActionListener(new SendListener());
    }

    public class Write {
        private PrintStream out;


        public Write() {
            try {
                out = new PrintStream(new BufferedOutputStream(
                        user.getSocket().getOutputStream(), 1024), false);
            } catch (IOException e) {
                System.err.println(e);
            }
        }


        public void send(String message) {
            if (message != null) {
                out.println(message);
                out.flush();


                incomingMessages.setText(new String(incomingMessages.getText() + "\nMe: " + message));
            }
        }
    }


    public class SendListener implements ActionListener {
        private Write write = new Write();
        private String toSend;


        @Override
        public void actionPerformed(ActionEvent event) {
            toSend = messageToSend.getText();


            if (toSend != null || event.getActionCommand() == "\n") {
                write.send(toSend);
            }


            messageToSend.setText(new String(""));
        }
    }
}

You need to create a new Runnable class, whose data members consist of a Socket and its input and output streams. 您需要创建一个新的Runnable类,其数据成员由一个Socket及其输入和输出流组成。 This class is used on the server side. 此类在服务器端使用。 Its run() method is responsible for all I/O to that client. 它的run()方法负责该客户端的所有I / O。 Then your accept() loop just looks like this: 然后,您的accept()循环如下所示:

while (true)
{
    new Thread(new ConnectionHandler(serverSocket.accept())).start();
}

where ConnectionHandler implements Runnable as above. 其中ConnectionHandler实现上述的Runnable

simply what you need to do is after accepting the request from the client (Using main thread), then the request pass to a new thread with the client socket and process the request inside the new thread. 简单地,您需要做的就是在接受来自客户端的请求之后(使用主线程),然后将请求传递到带有客户端套接字的新线程,并在新线程内处理该请求。 So the main thread is free to accept new requests. 因此,主线程可以自由接受新请求。

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

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