我想在java中将图像从客户端发送到服务器。我发现一种方法是使用套接字。我的代码如下:
服务器端:线程等待客户端套接字并在客户端连接时接收图像:
@Override
public void run() {
while (running) {
try(Socket clientSocket = serverSocket.accept();
PrintWriter outText = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader intText = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
) {
try {
// Get image info
String imageInfo = inText.readLine();
BufferedImage image = ImageIO.read(ImageIO.createImageInputStream(clientSocket.getInputStream()));
// Handle input
String[] split = imageInfo.split(";");
String typeStr = split[0];
String name = split[1];
ServerImageType type = ServerImageType.fromInt(Integer.valueOf(typeStr));
// Save image
SaveImageThread saveImageThread = new SaveImageThread(image, name, type);
saveImageThread.start();
// Respond
outText.println(name + " OK");
} catch (IOException e) {
System.err.out("The server is in pain: " + e);
}
}
}
try {
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
客户方:
public void sendImage(BufferedImage image, String name, ServerImageType imageType) throws IOException {
try(Socket clientSocket = new Socket(serverName, txPort);
PrintWriter outText = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader inText = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))
) {
// Send image info
String imageInfo = imageType.getId() + ";" + name;
outText.println(imageInfo);
// Send image
ImageIO.write(image, "JPG", clientSocket.getOutputStream());
// Receive acknowledgement
String input = inText.readLine();
System.out.println("Server answered: " + input);
}
}
问题:服务器卡在 ImageIO.read(... 行..任何想法?
答案 0 :(得分:0)
我没有看到clientSocket.getOutputStream()。flush()。