ServerSocket与客户端Socket的通信

时间:2014-01-01 18:16:47

标签: java multithreading sockets client

我正在尝试使用中央服务器和单独的聊天客户端进行多线程聊天程序。服务器有两个角色:从所有聊天客户端读取传入消息,并将完整列表输出回客户端。服务器正确接收来自客户端的输入并将其打印出来。但是客户端没有收到列表。为了便于查看影响服务器到客户端通信的代码段,我使用星号标记了它们。

服务器代码:

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

客户代码:

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

同时运行太多ClientOuputConnection线程会出现问题吗?或者是我在一台计算机上运行所有这些客户端的问题?

1 个答案:

答案 0 :(得分:0)

让我试一试。你试过调试代码吗? 您首先启动Clientcon,然后启动ClientOut。 当ClientOut启动时,它会转到此循环

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

您的ChatServer有可能在arraylist中没有任何内容。它会退出while循环。不确定这是否正确。在查看代码时,我认为这可能是一个问题。