【问题标题】:Client-Server application JAVA, server don't receive data客户端-服务器应用JAVA,服务器不接收数据
【发布时间】:2012-07-13 19:02:31
【问题描述】:

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

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

【问题讨论】:

  • 比较你对这个工作的方法example
  • 问题可能出在客户端代码上,这里还有一个相关的example。希望你不要屏蔽你的Event Dispatch Thread !!
  • 如果可能,您应该发布客户端代码。

标签: java swing client-server


【解决方案1】:

你的 actionPerformed 方法只是链接服务器,什么都不做。

发送消息后服务器关闭。

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

如果客户端不发送任何消息,代码将中断,那么你关闭了服务器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    相关资源
    最近更新 更多