3

I have a problem when the client send data to the server. When I send data from the server to the client everything is okay. I received this message: "client receive: message" but then when I send "client's message", my server do not receive it.

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

1 回答 1

1

你的 actionPerformed 方法只是链接服务器而不做任何事情。

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

观看:while ((inputLine = in.readLine()) != null)

如果客户端不发送任何消息,代码将中断,然后您关闭服务器。

于 2012-10-09T03:26:39.570 回答