【问题标题】:Socket server, I don't receive the message sent by my Server套接字服务器,我没有收到我的服务器发送的消息
【发布时间】:2014-05-27 20:51:32
【问题描述】:

我有一个客户端-服务器连接..

当我的服务器连接到客户端时,它必须通过输出流发送一条消息,然后在从输入流接收到消息时打印它。但是当客户端连接时,我收到“已连接”消息,但我没有看到“这是一条短信\n”发送给我的服务器

这是我的服务器:

public class Server1 extends JFrame{
    static JTextArea testoarea;
    static Socket socket;
    static ServerSocket server;

    public Server1(){
        testoarea = new JTextArea();
        add(new JScrollPane(testoarea));
        setSize(600, 700);
        setVisible(true);
    }

    public static void main(String[] args) {
        Server1 server1 = new Server1();
        server1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        inizzializza();
        connetti();
    }


    private static void inizzializza(){
        try {
            server = new ServerSocket(7100);
            showMessage("Server Iniziato\n");
        } catch (IOException e) {
            System.out.println(e);
        }   
    }


    private static void connetti() {
        try {
            socket = server.accept();
            showMessage("Connected \n"); 

            PrintWriter output = new PrintWriter(socket.getOutputStream());
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            output.println("this is a Test message\n");
            showMessage(input.readLine().toString()); 
            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    private static void showMessage(final String text) {
        // TODO Auto-generated method stub
        SwingUtilities.invokeLater(
            new Runnable() {
                public void run() {
                    testoarea.append(text);
                }
            }
        );
    }
}

这是我回来的:

【问题讨论】:

  • 下次请尽量不要从编辑器中复制/粘贴文本,因为stackoverflow代码中的一个制表符实际上等于四个空格。
  • @Theolodis 哦对不起,我不知道..
  • 没问题,我帮你修好了。
  • 哦,问题可能是你收到消息后正在刷新,但我猜你只有刷新请求才能得到答案。 TL;DR:output.println("this is a Test message\n"); output.flush(); 解决了您的问题。
  • 两点说明:您当然不想在output.println() 通话中添加“\n”。其次,如果你想调用output.flush(),你想在input.readLine()之前调用它

标签: java sockets


【解决方案1】:

您的input.readLine() 在您的服务器端 客户端输入流上。这意味着它会尝试读取来自客户的收入消息。

如果您不想从客户端读取服务器发送给客户端的消息(我认为您想要的,但我可能误解了)。您必须获得 client 套接字输入流。 你得到的套接字你可能在某个地方调用过:

Socket clientSocket = new Socket("localhost", 7100);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-17
    • 2018-09-24
    • 2021-10-05
    • 2015-12-10
    • 2014-07-05
    • 1970-01-01
    • 2015-06-21
    相关资源
    最近更新 更多