Java程序不接收/发送/从服务器/客户端发送信息

时间:2014-03-13 21:15:55

标签: java sockets inputstream

我正在尝试用服务器和单个客户端编写一个简单的聊天程序。我可以通过端口转发将它们连接在一起,并且每个都可以收到一条消息。但是,一旦连接,我希望能够同时发送和接收消息。出于某种原因,这根本不会发生。这是我的代码。

客户端:

// Client class
public class Client
{
public static void main(String [] args)
{
    // Get server name, port number, and username from command line
    String serverName = args[0];
    int port = Integer.parseInt(args[1]);
    String username = args[2];
    try
    {
        // Print welcome message and information
        System.out.println("Hello, " + username);
        System.out.println("Connecting to " + serverName + " on port " + port);
        // Create the socket
        Socket client = new Socket(serverName, port);
        // Print connected information
        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        // Out to server
        OutputStream outToServer = client.getOutputStream();
        DataOutputStream out = new DataOutputStream(outToServer);
        // Print message to server
        out.writeUTF("Hello from " + client.getLocalSocketAddress());
        // In from server
        InputStream inFromServer = client.getInputStream();
        DataInputStream in = new DataInputStream(inFromServer);
        // Print message from server
        System.out.println("Server says " + in.readUTF());
        // Begin reading user input to send to the server
        Scanner chat = new Scanner(System.in);
        String lineTo;
        String lineFrom;
        // Keep the program open unless the user types endchat
        while (!chat.nextLine().equals("endchat"))
        {
            // Read any messages coming in from the server          
            lineFrom = String.valueOf(in.readUTF());
            System.out.println(lineFrom);
            // Write any messages to the client
            lineTo = chat.nextLine();
            out.writeUTF(lineTo);
        }
        // Close the connection
        client.close();
    }catch(IOException e)
    {
        e.printStackTrace();
    }
}

}

服务器:

// Server class
public class Server extends Thread
{
private ServerSocket serverSocket;
private String username;

// Create server
public Server(int port, String username) throws IOException
{
    serverSocket = new ServerSocket(port);
    this.username = username;
}
// Keep running
public void run()
{
    try
    {
        // Print info
        System.out.println("Hello, " + username);
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        // Accept the client
        Socket server = serverSocket.accept();
        // To client
        OutputStream outToClient = server.getOutputStream();
        DataOutputStream out =  new DataOutputStream(outToClient);
        // From client
        InputStream inFromClient = server.getInputStream();
        DataInputStream in = new DataInputStream(inFromClient);
        // Print info when connected
        System.out.println("Just connected to " + server.getRemoteSocketAddress());         
        // Print message from client
        System.out.println("Client says: " + in.readUTF());
        // Print message to client
        out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress());
        // Tell client they may begin chatting
        out.writeUTF("You may now begin chatting! Type endchat to end the chat!");
        // Start reading user input
        Scanner chat = new Scanner(System.in);
        String lineFrom;
        String lineTo;
        // Keep the program open as long as the user doesn't type endchat
        while (!chat.nextLine().equals("endchat"))
        {
            // Read from client
            lineFrom = String.valueOf(in.readUTF());
            System.out.println(lineFrom);
            // Send to client
            lineTo = chat.nextLine();               
            out.writeUTF(lineTo + "\n");
        }
    }catch(SocketTimeoutException s)
    {
        System.out.println("Socket timed out!");
    }catch(IOException e)
    {
        e.printStackTrace();
    } 
}
public static void main(String [] args)
{
    // Get port number and username from command line
    int port = Integer.parseInt(args[0]);
    String username = args[1];
    try
    {
        // Create and start new Server
        Thread t = new Server(port, username);
        t.start();
    }catch(IOException e)
    {
        e.printStackTrace();
    }
}

}

编辑:我在发送邮件时将新行字符添加到我的Server类中。我现在正在我的客户端类中收到消息,但我收到的消息是奇怪的字符。

2 个答案:

答案 0 :(得分:0)

首先将您的读写分开并写入不同的方法

private String read(Server server){
// From client
        InputStream inFromClient = server.getInputStream();
        DataInputStream in = new DataInputStream(inFromClient);
.....
 return message
}

private void write(Server server, String message){
 OutputStream outToClient = server.getOutputStream();
        DataOutputStream out =  new DataOutputStream(outToClient);

......     }

现在使用main / run方法在读/写之间切换。 如果客户端写入,它应该等待读取响应,并且与服务器相同。

你可以在" endChat"不是真的。

这很简单,但它应该让你去。

答案 1 :(得分:0)

您可以使用类似的内容同时发送和接收消息。

new Thread(){
    public void run(){
        try{
            while (!chat.nextLine().equals("endChat")){
                System.out.println(in.readUTF());
            }
        }catch(Exception error){error.printStackTrace();}
    }
}.start();

new Thread(){
    public void run(){
        try{
            while (!chat.nextLine().equals("endChat")){
                out.writeUTF(chat.nextLine());
            }
        }catch(Exception error){error.printStackTrace();}
    }
}.start();