简体   繁体   English

ServerSocket与客户端Socket的通信

[英]ServerSocket communication to client Socket

I am trying to make a multi-threaded chat program with a central server and separate chat clients. 我正在尝试使用中央服务器和单独的聊天客户端制作多线程聊天程序。 The server has two roles: read incoming messages from all the chat clients and output the complete lists back to the clients. 该服务器具有两个角色:从所有聊天客户端读取传入消息,并将完整列表输出回客户端。 The server correctly receives input from clients and prints it out. 服务器正确地从客户端接收输入并将其打印出来。 However the clients are do not receive the list. 但是,客户端不会收到该列表。 In order to easily see the code segments that affect server to client communication I have marked them with an asterisk. 为了轻松查看影响服务器到客户端通信的代码段,我在其上标记了一个星号。

Server Code: 服务器代码:

import java.net.*;
import java.util.*;
import java.io.*;
import java.lang.*;

public class ChatServer {
    public static ArrayList<String> messages =
        new ArrayList<String>();

    public static void main(String[] args) {
        int portNumber = Integer.parseInt(args[0]);
        Scanner cin = new Scanner(System.in);

        ServerSocket serverSocket;
        try {
            serverSocket = new ServerSocket(portNumber); //*
        }catch (IOException ex) {
            System.out.println("Server socket creation failed");
            //ex.printStackTrace();
            return;
        }

        try {
            int maxConnections = 10;
            int curConnections = 0;
            while (curConnections++ < maxConnections) {
                Socket clientSocket = serverSocket.accept();

                ClientConnection clientCon = new ClientConnection(clientSocket);
                Thread clientConT = new Thread(clientCon);
                //clientConT.setPriority(curConnections+1);
                clientConT.start();

                ClientOutputConnection clientOut = new          //*
                    ClientOutputConnection(clientSocket);   
                Thread clientOutT = new Thread(clientOut);      //*
                //clientOutT.setPriority((curConnections+1)*2);
                clientOutT.start();                             //*


                System.out.println("Client "+curConnections+" Connected");
            }
        }catch (IOException ex) {
            System.out.println("Client connection failed");
            ex.printStackTrace();
        }
    }
}

class ClientConnection implements Runnable {
    Socket clientSocket;

    public ClientConnection(Socket clientSocketT) {
        clientSocket = clientSocketT;
    }

    public void run() {
        try {
            System.out.println("ClientConnection server running");
            BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));

            while (true) {
                String lineIn = null;
                if ((lineIn = in.readLine()) != null) {
                    System.out.println(lineIn);
                    ChatServer.messages.add(lineIn);
                }

                if (lineIn.equalsIgnoreCase("exit") || 
                    lineIn.equalsIgnoreCase("close"))
                    return;
            }
        }catch (Exception ex) {
            ex.printStackTrace();
        }
    } 
}

class ClientOutputConnection implements Runnable {
    private Socket clientSocket;

    public ClientOutputConnection(Socket clientSocketT) {
        clientSocket = clientSocketT;
    }

    public void run() {
        try {
            PrintWriter out = new PrintWriter(
                clientSocket.getOutputStream(), true);

            System.out.println("ClientOutputConnection running");

            int lastMssg = 0;

            while (true) {
                try {
                    //System.out.println(ChatServer.messages);
                    while (lastMssg < ChatServer.messages.size()) {
                        out.println(ChatServer.messages.get(lastMssg)+"\n");
                        //System.out.println(ChatServer.messages.get(lastMssg));
                        lastMssg++;
                    }

                    //Thread.sleep(10);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }catch(IOException ex) {
            ex.printStackTrace();
        }
    }
}

Client Code: 客户代码:

import java.net.*;
import java.util.*;
import java.io.*;
import static java.lang.System.*;

public class ChatClient {
    public static void main(String[] args) {
        int portNumber = Integer.parseInt(args[0]);
        Scanner cin = new Scanner(System.in);

        PrintWriter out;
        Socket clientSocket;

        try {
            System.out.println("Break 1");
            clientSocket = new Socket("localhost", portNumber);
            System.out.println("Break 2");
            out = new PrintWriter(clientSocket.getOutputStream(), true);
        }catch (Exception ex) {
            System.out.println("PrintWriter creation failed");
            ex.printStackTrace();
            return;
        }

        //Initializes reader for server
        BufferedReader in = null;  //*
        try {
            in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));   //*
        }catch (IOException ex) {
            ex.printStackTrace();
        }

        System.out.print("Enter your username: ");
        String username = cin.nextLine();
        out.println();

        ServerListener sl = new ServerListener(in, username);   //*
        Thread slT = new Thread(sl);                            //*
        //slT.setPriority(1);
        slT.start();                                            //*

        ServerOutput so = new ServerOutput(username, out);
        Thread soT = new Thread(so);                        
        //soT.setPriority(2);
        soT.start();                                        
    }
}

class ServerOutput implements Runnable {
    private String username;
    private PrintWriter out;

    public ServerOutput(String usernameT, PrintWriter outT) {
        username = usernameT;
        out = outT;
    }

    public void run() {
        Scanner cin = new Scanner(System.in);
        while (true) {
            String line = cin.nextLine();
            if (line.equalsIgnoreCase("close")) {
                out.close();
                return; 
            }

            out.write("<"+username+"> "+line+"\n");
            out.flush();

            try { Thread.sleep(10); }catch(Exception e){};
        }
    }
}

class ServerListener implements Runnable {
    private BufferedReader in;
    private String username;

    public ServerListener (BufferedReader inT, String usernameT) {
        in = inT;
        username = usernameT;
    }

    public void run() {
        System.out.println("ServerListener running");
        String line = null;
        try {
            while (true){
                //System.out.println(in.readLine());
                while ((line = in.readLine()) != null)
                    //if (line.indexOf(username) != 1)
                        System.out.println(line);
            }
        }catch (IOException ex) {
            //System.out.println("Doesnt work");
            ex.printStackTrace();
        }
    }
}

Could it be an issue with running too many ClientOuputConnection threads at the same time? 同时运行太多ClientOuputConnection线程是否会引起问题? Or is it an issue that I am running all of these clients on one computer? 还是我在一台计算机上运行所有这些客户端的问题?

Let me give a try. 我来试试看 Did you try debugging the code. 您是否尝试调试代码。 you are first starting the Clientcon and then ClientOut. 您首先要启动Clientcon,然后再启动ClientOut。 when ClientOut is started, it goes to this while loop 启动ClientOut时,转到此while循环

while (true) {
                try {
                    //System.out.println(ChatServer.messages);
                    while (lastMssg < ChatServer.messages.size()) {
                        out.println(ChatServer.messages.get(lastMssg)+"\n");
                        //System.out.println(ChatServer.messages.get(lastMssg));
                        lastMssg++;
                    }

                    //Thread.sleep(10);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }

There is a chance that your ChatServer does not have anything in the arraylist.and it exits out of the while loop. 您的ChatServer有可能在arraylist中没有任何内容,并且退出while循环。 not sure whether this is right. 不确定这是否正确。 On looking at the code, I thought this might be an issue. 在查看代码时,我认为这可能是一个问题。

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

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