我试图发送多个图像从客户端到服务器。 Client有两个线程
线程1正在截图
线程2发送截图服务器
这段代码正在2个截图。但只有第一个屏幕截图成功保存在服务器上。请帮我发送并保存多个图像到服务器。
没有错误,没有例外。
输出:
线程1正在运行...
线程2正在运行...
线程1正在运行...
线程2正在运行...
客户端
abstract class ScreenCapture implements Runnable{
static BufferedImage screencapture;
static ByteArrayOutputStream baos;
static byte[] ImageInBytes;
public static void main(String args[]) throws
AWTException, IOException, InterruptedException {
// Open your connection to a server, at port 1234
final Socket ClientSocket = new Socket("localhost",1234);
final DataOutputStream dos= new DataOutputStream(ClientSocket.getOutputStream());
DataInputStream in = new DataInputStream(ClientSocket.getInputStream());
baos = new ByteArrayOutputStream();
try{
//First thread that is Taking screenshot
Thread TakeScreenShotthread = new Thread()
{
public void run() {
// Capture Screen using BufferedImage Library
try {
screencapture = new Robot().createScreenCapture(
new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
System.out.println("thread1 is running...");
} catch (HeadlessException e) {
e.printStackTrace();
} catch (AWTException e) {
e.printStackTrace();
}
}
};
//Thread 2 that is Sending Screenshot to server
Thread sendingScreenShotThread =new Thread() {
public void run() {
//Sending Screen to Server
try {
ImageIO.write(screencapture, "jpg", baos);
ImageInBytes = baos.toByteArray();
dos.write(ImageInBytes);
// File Rif = new File(System.currentTimeMillis() + ".jpg");
//ImageIO.write(screencapture, "jpg", Rif);
System.out.println("thread2 is running...");
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
baos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
TakeScreenShotthread.start();
TakeScreenShotthread.sleep(1000);
sendingScreenShotThread.start();
sendingScreenShotThread.sleep(1000);
TakeScreenShotthread.run();
sendingScreenShotThread.run();
}finally
{
//Closing Clients
in.close();
baos.close();
ClientSocket.close();
}
}
}
服务器
public class ServerConnection
{
public static void main(String args[]) throws IOException
{
ServerSocket serversock = new ServerSocket(1234);
Socket clientSocket = null;
BufferedReader BF_RecievingGUID;
clientSocket = serversock.accept();
InputStream in=clientSocket.getInputStream();
OutputStream out = null;
try{
boolean processing=true;
while(processing)
{
try {
byte[] buffer = new byte[1024];
out = new BufferedOutputStream(new FileOutputStream(path));
while ((in.read(buffer)) >= 0) {
out.write(buffer);
}
System.out.println("Image file written successfully");
} catch (Exception e) {
}finally {
processing=false;
if (out != null) out.close();
}
}
}
finally{
BF_RecievingGUID.close();
out.close();
clientSocket.close();
serversock.close();
}
}
}
是如何你确定一个图像结束和一个新的开始?如果您自己不这样做,读者很可能会读取所有数据作为第一张图像的一部分。我也会检查你正在调用的库是否关闭任何流。 – 2015-02-23 08:05:00
我们如何确定一个图像结束并开始一个新图像?请帮忙 – Heights 2015-02-23 08:21:21
为什么你要开始一个线程来处理套接字然后在接下来的语句中做I/O?这不可能工作。反思。 – EJP 2015-02-23 08:37:15