当我从客户端向服务器发送字符串时,服务器总是抛出
java.net.SocketException:连接重置
如果我发送一个Integer或除String之外的其他类型,则不会抛出异常并且程序运行得非常好。
客户类:
import java.io.*;
import java.net.*;
public class TestingClient {
public static void main(String[] args) {
try {
Socket clientSocket = new Socket("localhost", 9998);
DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
outputStream.flush();
outputStream.writeBytes("hello");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器类:
import java.io.*;
import java.io.IOException;
import java.net.*;
public class TestingServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(9998);
Socket connectionToClient = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(connectionToClient.getInputStream()));
System.out.println(input.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
好吧,"hello"
不是byte[]
。在客户端上,使用DataOutputStream.writeUTF(String)
然后String
撰写flush()
。像
outputStream.writeUTF("hello");
outputStream.flush();
并且在服务器上,您无法使用BufferedReader
。您需要DataInputStream.readUTF()
DataInputStream dis = new DataInputStream(
connectionToClient.getInputStream());
System.out.println(dis.readUTF());