在客户端和服务器之间发送字符串时出错

Error When Sending String Between Client And Server

当我从客户端向服务器发送字符串时,服务器总是抛出一个

java.net.SocketException: Connection reset

如果我发送 Integer 或除 String 以外的其他类型,则不会抛出异常并且程序运行绝对正常。

客户Class:

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


    }

}

服务器Class:

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


    }

}

嗯,"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());