我正在尝试使用java程序读取数据并将数据写入服务器。我正在使用控制台写入数据。我可以成功地将数据写入服务器,但是当我尝试读取服务器发送的数据时出现问题。
import java.io.*;
import java.net.*;
public class EMSSocketConnection {
public static void main(String[] args) throws Exception {
createSocket();
}
private static void sendMessage(DataOutputStream out) throws Exception
{
try
{
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userOutput;
while ((userOutput = stdIn.readLine()) != null)
{
out.writeBytes(userOutput);
out.write('\n');
}
out.flush();
}
catch(Exception ex)
{
System.out.println(ex.getStackTrace());
}
finally
{
out.close();
}
}
private static void readResponse(DataInputStream in) throws Exception
{
try
{
byte[] data = new byte[1024];
in.readFully(data);
System.out.println(data);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
finally
{
in.close();
}
}
private static void createSocket()
{
try
{
int port = 2345;
InetAddress address = InetAddress.getByName("192.100.100.129");
final Socket client = new Socket(address, port);
final DataOutputStream out = new DataOutputStream(client.getOutputStream());
final DataInputStream in = new DataInputStream(client.getInputStream());
System.out.println("Successfully Connected");
new Thread() {
public void run() {
synchronized(client)
{
try {
while(true)
{
sendMessage(out);
readResponse(in);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
}.start();
}
catch(Exception ex)
{
ex.getStackTrace();
}
}
}
谁能告诉我如何成功地从服务器读取数据?
最佳答案
您的服务器是否将 1024 字节写入其输出?如果没有,您的代码
byte[] data = new byte[1024];
in.readFully(data);
将无限期地阻塞并等待。
更好的习惯用法是这样做:
byte [] data = new byte[in.available()];
in.readFully(data);
您不能随意地从流中读取数据并假设您将获得预期的数据。流会受到 IO 延迟和缓冲的影响,您需要意识到这一点,尤其是在处理网络 IO 时。
关于java - Java无法从服务器读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10008994/