不使用Java套接字中的ObjectInputStream读取任何内容
我创建了一个简单的服务器和一个客户端,但是服务器无法读取从客户端发送的任何内容。在发送字符串后,我还添加了一个print语句,但它也无法打印不使用Java套接字中的ObjectInputStream读取任何内容,java,sockets,serversocket,Java,Sockets,Serversocket,我创建了一个简单的服务器和一个客户端,但是服务器无法读取从客户端发送的任何内容。在发送字符串后,我还添加了一个print语句,但它也无法打印 public class Server { public static void main(String[] args) throws IOException, ClassNotFoundException { ServerSocket serverSocket = new Serve
public class Server {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket serverSocket = new ServerSocket(6666);
Socket clientSocket = serverSocket.accept();
System.out.println("accepting client at address " + clientSocket.getRemoteSocketAddress());
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
String input = (String) in.readObject();
System.out.println(input);
out.writeObject("Received");
out.flush();
}
}
下面是客户端,我只想发送一个字符串“???不发送”:
如果我只是使用InputStream并使用缓冲区读取字节,我尝试了其他方法,如: 这是客户端代码: 上面两个链接中的代码可以工作。但是,如果我尝试使用ObjectInputStream,它将不起作用: 这是服务器: 这是客户: 这是我要发送的消息对象:
有人能给我解释一下吗?谢谢 要从套接字读取字符串,请使用以下方法:
DataInputStream input=newdatainputstream(clientSocket.getInputStream());
字符串消息=input.readUTF()代码>
您可以从一个套接字打开多个流,因此,如果您想读取真正需要ObjectInputStream的其他内容,也可以打开它。不要忘记正确关闭流和套接字。要从套接字读取字符串,请使用以下方法:
DataInputStream input=newdatainputstream(clientSocket.getInputStream());
字符串消息=input.readUTF()代码>
您可以从一个套接字打开多个流,因此,如果您想读取真正需要ObjectInputStream的其他内容,也可以打开它。不要忘记正确关闭流和插座
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Client client = new Client();
client.sentInfo();
}
private static class Client {
private ObjectInputStream objectInputStream;
private ObjectOutputStream objectOutputStream;
public Client() throws IOException {
Socket socket = new Socket("127.0.0.1", 6666);
this.objectInputStream = new ObjectInputStream(socket.getInputStream());
this.objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
}
public void sentInfo() throws IOException, ClassNotFoundException {
this.objectOutputStream.writeObject("?????does not send");
this.objectOutputStream.flush();
System.out.println("????????");
Message resp = (Message) this.objectInputStream.readObject();
System.out.println(resp.getMessage());
}
}
}