【问题标题】:Java program not receiving/sending information to/from server/clientJava程序不接收/发送信息到/从服务器/客户端
【发布时间】:2014-03-13 21:15:55
【问题描述】:

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

客户:

// 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 类中。我现在在我的客户端类中接收到消息,但我收到的消息是奇怪的字符。

【问题讨论】:

  • 据我从您的代码中了解到,为了让服务器打印来自客户端的消息,您还需要在服务器端输入一些内容。你知道吗?
  • 是的,我知道这一点。我最终会修复它并按照 myqyl4 的建议模块化我的代码。

标签: java sockets inputstream


【解决方案1】:

首先将您的读写分离为不同的方法

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”不正确的情况下执行此操作。

这很简单,但它应该能让你继续前进。

【讨论】:

  • 谢谢,这是有道理的。我打算最终这样做。我认为我的问题与插入换行符有关。请参阅我更新的服务器类。我现在可以在我的客户端类中接收消息,但它们的字符很奇怪。
【解决方案2】:

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

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

【讨论】:

  • 谢谢,我试试看!
  • 由于某种原因,它不喜欢 Thread() 之后和 .start() 之前的括号;这是正确的语法吗?
  • 括号内必须有一个 public void run(){//put code here},我一定是忘了把它放在我的答案中,我会编辑它。抱歉花了我这么久才回复
猜你喜欢
  • 1970-01-01
  • 2014-05-12
  • 2012-12-03
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多