62,623
社区成员
发帖
与我相关
我的任务
分享public class Server extends JFrame{
//private MyCanvas canvas;
private ServerSocket ss;
private Socket socket=null;
private DataInputStream is;
private byte[]imageContent;
private FileOutputStream fos;
private static MyPanel canvas;
private static Server f;
private static ConcurrentLinkedDeque queue;
public static void main(String[] args) throws Exception {
f = new Server();
canvas = f.new MyPanel();
queue=new ConcurrentLinkedDeque();
f.add(canvas);
f.setSize(500, 500);
f.setVisible(true);
f.startThread();
}
class MyPanel extends JPanel
{
@Override
public void paint(Graphics g) {
super.paint(g);
g.clearRect(0, 0, getWidth(), getHeight());
BufferedImage image=(BufferedImage) queue.poll();
g.drawImage(image, 0, 0, null);
if(image!=null)
System.out.println("paint :"+image.toString());
}
}
public void startThread() throws Exception
{
try {
ss=new ServerSocket(9991);
socket=ss.accept();
if(socket!=null)
{
System.out.println(socket.getLocalAddress());
}
is=new DataInputStream(socket.getInputStream());
int hasRead=-1;
while(true)
{
int sum=0;
int len=is.readInt();
System.out.println("length:"+len);
imageContent=new byte[len];
while(sum<len)
{
hasRead=is.read(imageContent,sum,len-sum);
sum+=hasRead;
}
String fileName = "IMG_"
+ new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())
.toString() + ".jpg";
File imgFile = new File("D:\\"+fileName);
if(!imgFile.exists())
{
imgFile.createNewFile();
}
fos = new FileOutputStream(imgFile);
fos.write(imageContent);
BufferedImage image=ImageIO.read(imgFile);
queue.add(image);
canvas.repaint();
System.out.println(imgFile.getName());
System.out.println("sum "+sum);
//线程睡眠100ms,这样不会造成数据读的错误
Thread.sleep(100);
}
} catch (IOException e) {
System.out.println("__"+e.getMessage());
}
}
}


