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

时间:2015-04-22 01:36:04

标签: java network-programming

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

  

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


    }

}

1 个答案:

答案 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());