无法在 Java Socket/Client 之间读写 [英] Not able to read and write between Java Socket/Client

查看:41
本文介绍了无法在 Java Socket/Client 之间读写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 java.net 在 Java 中的服务器和客户端之间建立连接.我设法连接,但没有发送任何数据.我已经粘贴了代码和输出:

服务器代码:

ServerSocketwelcomeSocket = new ServerSocket(999);Socket connectionSocket =welcomeSocket.accept();System.out.println("连接到:" + connectionSocket.toString());DataOutputStream outToClient = newDataOutputStream(connectionSocket.getOutputStream());outToClient.writeBytes("测试连接");

客户代码:

Socket clientSocket = new Socket("130.236.248.52", 999);BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));modifiedSentence = inFromServer.readLine();System.out.println("[来自服务器:]" + modifiedSentence);

服务器输出:连接到:Socket[addr=/130.236.248.54,port=51535,localport=999]

客户端输出:

解决方案

  1. 使用 BufferedWriter 写入文本(就像您使用 BufferedReader 读取文本一样)
  2. 在编写器上调用 flush() 以强制输出通过
  3. 如果您在客户端调用 readLine(),则需要有一个要读取的行尾.

<前>BufferedWriter outToClient = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));outToClient.write("测试连接");outToClient.newLine();outToClient.flush();

I am trying to establish a connection between a server and a client in Java, using java.net. I manage to connect, but not to send any data. I have pasted the code and the outputs:

Server Code:

ServerSocket welcomeSocket = new ServerSocket(999);
Socket connectionSocket = welcomeSocket.accept();
System.out.println("Connected to: " + connectionSocket.toString());
DataOutputStream outToClient = newDataOutputStream(connectionSocket.getOutputStream());
outToClient.writeBytes("Testing connection");

Client Code:

Socket clientSocket = new Socket("130.236.248.52", 999);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
modifiedSentence = inFromServer.readLine();
System.out.println("[From server:] " + modifiedSentence);

Server output: Connected to: Socket[addr=/130.236.248.54,port=51535,localport=999]

Client output:

解决方案

  1. Use a BufferedWriter to write text (just like you're using a BufferedReader to read text)
  2. Call flush() on your writer to force the output to go through
  3. If you're calling readLine() on the client side, there needs to be an end-of-line to read.

    BufferedWriter outToClient = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
    outToClient.write("Testing connection");
    outToClient.newLine();
    outToClient.flush();

这篇关于无法在 Java Socket/Client 之间读写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆