如何在java中使用套接字发送/接收对象[重复]
Posted
技术标签:
【中文标题】如何在java中使用套接字发送/接收对象[重复]【英文标题】:how to send/receive Objects using sockets in java [duplicate] 【发布时间】:2015-02-28 10:21:40 【问题描述】:当我在 CMD 窗口中执行我的代码时,它在客户端模式下不起作用,正好在以下行:
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
这一行的程序块,但不要停止或发出错误信号:
我有 3 个班级:Client
、Server
、Message
客户端类:
package client;
// Organize imports
public class Client
public static void main(String[] args) throws UnknownHostException,
IOException, ClassNotFoundException
System.out.println("welcome client");
Socket socket = new Socket("localhost", 4444);
System.out.println("Client connected");
ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Ok");
Message message = new Message(new Integer(15), new Integer(32));
os.writeObject(message);
System.out.println("Envoi des informations au serveur ...");
ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
Message returnMessage = (Message) is.readObject();
System.out.println("return Message is=" + returnMessage);
socket.close();
服务器
这是Server
类的代码
package Sockets;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
public static final int port = 4444;
private ServerSocket ss = null;
public void runServer() throws IOException, ClassNotFoundException
ss = new ServerSocket(port);
System.out.println("le systeme est pret pour accepter les connexions");
Socket socket = ss.accept();
ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
Message m = (Message) is.readObject();
doSomething(m);
os.writeObject(m);
socket.close();
private void doSomething(Message m)
m.setResult(new Integer(m.getA().intValue()*m.getB().intValue()));
public static void main(String[] args) throws ClassNotFoundException, IOException
new Server().runServer();
留言
这是我的对象,我通过实现接口Serializable
实现了Serializable
import java.io.Serializable;
public class Message implements Serializable
private static final long serialVersionUID = -5399605122490343339L;
private Integer A;
private Integer B;
private Integer Result;
public Message(Integer firstNumber, Integer secondNumber )
this.A = firstNumber;
this.B = secondNumber;
public Integer getA()
return A;
public Integer getB()
return B;
public void setResult(Integer X)
Result = X;
【问题讨论】:
【参考方案1】:您需要在ObjectInputStream
之前在两端创建ObjectOutputStream
,原因在Javadoc 中有关对象流标头的描述。
【讨论】:
它有效!谢谢 非常感谢!以上是关于如何在java中使用套接字发送/接收对象[重复]的主要内容,如果未能解决你的问题,请参考以下文章