客户端-服务器应用程序JAVA,服务器不接收数据

3

当客户端向服务器发送数据时,我遇到了问题。但是当我从服务器向客户端发送数据时,一切正常。我收到了这条消息:“客户端接收:消息”,但是当我发送“客户端的消息”时,我的服务器没有接收到它。

import java.io.IOException;

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

public class Server {    
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(1);
        }

        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.exit(1);
        }

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                clientSocket.getInputStream()));
        String inputLine, outputLine;

        outputLine = "message";
        out.println(outputLine);

        while ((inputLine = in.readLine()) != null) {
            System.out.println("server receive: " + inputLine);
            outputLine = "second message";
            out.println(outputLine);
        }

        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
    }
}


public void actionPerformed(ActionEvent e) {

    if (e.getSource() == startButton) {
        this.main.getContentPane().remove(homePanel);
        String name = this.name.getText();

        String result;            
        try {
            connectionToServer();
            if ((result = in.readLine()) != null) {
                System.out.println("client receive: " + result);
                out.println("client's message");
            }
        } catch(IOException err) {
            System.out.println("error");
        }

    }        
}

public void connectionToServer() throws IOException {
    try {
        this.socket = new Socket("localhost", 4444);
        this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
        this.out = new PrintWriter(this.socket.getOutputStream(), true);
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for the connection to: taranis.");
        System.exit(1);
    }        
}

2
请比较您的方法和这个可行的示例 - trashgod
1
问题可能出现在客户端代码,这里有一个相关的示例。希望您不要阻塞您的“事件分派线程”!! - nIcE cOw
2
如果可能的话,请发布客户端代码。 - JeanValjean
1个回答

1

你的actionPerformed方法只是连接了服务器,却没有做任何事情。

服务器在发送消息后关闭了。

注意:当客户端没有发送任何消息时,代码会中断,然后你关闭了服务器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接