[英]Sending BufferedImage over server to another java client
我正在尝试通过套接字服务器将BufferedImage发送到另一个客户端。 请在下面张贴我的代码。 当我运行服务器并通过发送客户端和接收客户端连接到服务器时,一切都就在那儿。 除非服务器已经打印了“名称正在尝试连接到:”,否则服务器甚至不应该接收任何内容,它只是坐在那里。 我不知道为什么它什么都不做。
发送的客户端: http : //pastebin.com/X4z55Hdp
收到的客户端: http : //pastebin.com/MB9qEyGy
发送和接收的服务器源:
package core;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import utilities.Tools;
public class Node implements Runnable {
private String name;
private Socket socket;
private boolean isApp;
public Node(Socket s, String name) {
this.setName(name);
this.setSocket(s);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Socket getSocket() {
return socket;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
public void run() {
while (true) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(),
true);
if (in.readLine() != null) {
// Tools.log("[INPUT] " + in.readLine());
String i = in.readLine();
if (i.contains("set name ")) {
String n = i.replace("set name ", "");
Tools.log("Changing " + name + " to " + n);
this.name = n;
if (n.contains("_app")) {
this.isApp = true;
}
} else {
String toFind = name + "_app";
if (isApp)
toFind = name.replace("_app", "");
Tools.log(name + " is attempting to connect to: "
+ toFind);
for (Node n : Server.nodes) {
if (n.getName().equals(toFind)) {
Tools.log(n.getName() + " found, sending data");
ObjectOutputStream outToNode = new ObjectOutputStream(
n.getSocket().getOutputStream());
ObjectInputStream inFromClient = new ObjectInputStream(
socket.getInputStream());
BufferedImage img = (BufferedImage) inFromClient
.readObject();
if (img != null) {
outToNode.writeObject(img);
}
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
BufferedImage必须被序列化。 您可以将图像转换为字节数组,一旦读取字节数组,就将其转换回图像。
当使用BufferedImage
调用writeObject()
时,发送方无疑会收到NotSerializableException
,因为BufferedImage
没有实现Serializable.
因此,您也无法从readObject()
调用中获得一个。 您必须将BufferedImage
转换为字节以进行发送,并在接收时再次返回。 看一下javax.imageio
的一种实现方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.