如何用1台服务器做多个客户端?

时间:2016-12-01 06:32:50

标签: java multithreading swing client-server java-io

这是我的服务器。顺便说一句,我正在使用JFrame。实际上,当我在PC 1中运行服务器然后是pc 2和PC 3上的客户端时,我有很多PC .PC 3客户端连接但服务器无法接收消息。虽然pc 2客户端已连接。

 package server;
 import java.net.*;
 import java.io.*;

public class FrmServer extends javax.swing.JFrame {

ServerSocket providerSocket;
Socket connection=null;
ObjectOutputStream out;
ObjectInputStream in;
String message;

//To run the connection
public void run(){

用于连接

    try{
        providerSocket = new ServerSocket(9090);
        msgArea.append("Waiting for connection....");
        connection = providerSocket.accept();

        out = new ObjectOutputStream(connection.getOutputStream());
        out.flush();

        in = new ObjectInputStream(connection.getInputStream());
        sendmessage("Connection is successful...");

        while(true){
           message = (String)in.readObject();

           if(!message.isEmpty())
               msgArea.append("\nClient: "+message);
        }

    }
    catch(Exception e){

    }

}

public void sendmessage(String msg){

    try{
        out.writeObject(msg);
        out.flush();
        msgArea.append("\nServer: "+msg);
    }catch(Exception e){

    }
}

/**
 * Creates new form FrmServer
 */
public FrmServer() {
    initComponents();
}

private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    sendmessage(txt.getText());
} 
public static void main(String args[]) {
FrmServer s = new FrmServer();
    s.setVisible(true);
    s.run();

}

客户端

package client;

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

public class FrmClient extends javax.swing.JFrame {

Socket requestSocket;
ObjectInputStream in;
ObjectOutputStream out;
String message;
/**
 * Creates new form FrmClient
 */
public FrmClient() {
    initComponents();
}

public void run(){

    try{
        requestSocket = new Socket("10.99.225.12",9090);
        msgArea.append("Connected to the server...");

        out = new ObjectOutputStream(requestSocket.getOutputStream());
        out.flush();

        in = new ObjectInputStream(requestSocket.getInputStream());

        while(true){
           message = (String)in.readObject(); 

           if(!message.isEmpty());
               msgArea.append("\nServer: "+message);
        }
    }
    catch(Exception e){

    }

}

public void sendmessage(String msg){

    try{
        out.writeObject(msg);
        out.flush();

        msgArea.append("\nClient: "+msg);
    }
    catch(Exception e){

    }

}

private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    sendmessage(txt.getText());
}  
private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
    // TODO add your handling code here:

    try{
        sendmessage("Got to go.. Goodbye!");
        in.close();
        out.close();
        requestSocket.close();
    }
    catch(Exception e){

    }

} 
public static void main(String args[]) {
FrmClient c = new FrmClient();
    c.setVisible(true);
    c.run();
}

2 个答案:

答案 0 :(得分:0)

您必须为每个套接字(客户端)创建一个线程,然后处理它们。

到目前为止,我发现,只有一个连接,因为您只初始化connection一次。

您可以创建一个列表,包含所有套接字以及从/向其输入/输出流写入/读取。

答案 1 :(得分:0)

您需要一个专用线程来持续监听连接。

接受连接后,为每个接受的连接创建两个线程,一个用于读取传入的数据,另一个用于将数据写入套接字。

这是对代码的简单修改,尽管可以用更好的方式编写。

  1. 让您的JFrame类实现Runnable。

    public class FrmServer extends javax.swing.JFrame implements Runnable
    
  2. 在JFrame类中实现run方法

    @Override
    public void run() {
        while (true) {
            try {
                msgArea.append("Waiting for connection....");
                connection = providerSocket.accept();
                new ConnectionWriter(connection, msgArea).start();
                new ConnectionReader(connection, msgArea).start();
            } catch (IOException ex) {
                System.err.out(ex);
            }
        }
    }
    
  3. 创建一个写入套接字的线程

    public class ConnectionWriter extends Thread {
    
        ObjectOutputStream out;
        Socket connection;
        JTextArea msgArea;
    
        public ConnectionWriter(Socket connection, JTextArea msgArea) {
            this.connection = connection;
            this.msgArea = msgArea;
        }
    
        @Override
        public void run() {
            try {
                out = new ObjectOutputStream(connection.getOutputStream());
                out.flush();
                sendmessage("Connection is successful...");
            } catch (IOException e) {
                System.out.println(e);
            }
        }
    
        public void sendmessage(String msg) {
    
            try {
                out.writeObject(msg);
                out.flush();
                msgArea.append("\nServer: " + msg);
            } catch (IOException e) {
                System.err.println(e);
            }
        }
    }
    
  4. 创建一个从套接字读取的线程。

    public class ConnectionReader extends Thread {
    
        ObjectInputStream in;
        Socket connection;
        JTextArea msgArea;
    
        public ConnectionReader(Socket connection, JTextArea msgArea) {
            this.connection = connection;
            this.msgArea = msgArea;
        }
    
        @Override
        public void run() {
            try {
                in = new ObjectInputStream(connection.getInputStream());
                while (true) {
                    String message = (String) in.readObject();
    
                    if (!message.isEmpty()) {
                        msgArea.append("\nClient: " + message);
                    }
                }
            } catch (IOException ex) {
                System.err.out(e);
            }
        }
    
    }