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

标签 java multithreading sockets

我有适用于一个客户端连接的代码。我需要的是服务器能够使用多线程方法处理多个客户端请求。

我找到了一些解决方案,但不符合我的要求,例如 this ,或 this

服务器.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

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

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(""));
        }
    }
}

最佳答案

您需要创建一个新的Runnable类,其数据成员由Socket及其输入和输出流组成。该类用于服务器端。它的 run() 方法负责该客户端的所有 I/O。然后你的 accept() 循环看起来像这样:

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

其中 ConnectionHandler 实现上述 Runnable

关于具有多个客户端的 Java Socket 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36732421/

相关文章:

java - 如何以编程方式移动 GWT Horizo​​ntalSplitPanel 的拆分器?

c++ - VC++ : Performance drop x20 when more threads than cpus but not under g++

C++,Qt - 锁定保护和返回对对象的不可分配引用的安全性

node.js - 与 Node 的 SMTP 连接

java - 在java中下载文件时出错-java.net.SocketException : Connection reset

java - C:将二维 double 组转换为java二维 double 组

java - 客户端的证书?

c# - 如何要求套接字等待更多数据到来

java - java java.text.ParseException 中的日期解析异常

python - 以最快的方式查找重复的图像