本帖最后由 吴林飞 于 2013-4-14 14:23 编辑
- import java.io.*;
- import java.net.*;
- /*
- 需求:实现多个客户端的并发上传图片
- */
- class ClientThread implements Runnable
- {
- private Socket s;
- ClientThread(Socket s)
- {
- this.s = s;
- }
- public void run()
- {
- int count = 1;
- try
- {
- InputStream in = s.getInputStream();
- File file = new File(count+".jpg");
- while(file.exists())
- {
- file = new File((++count)+".jpg");
- }
-
- FileOutputStream fos = new FileOutputStream(file);
- byte[] buf = new byte[1024];
- int len = 0;
- while((len=in.read(buf))!=-1)
- {
- fos.write(buf,0,len);
- }
- //s.shutdownInput();
- OutputStream out = s.getOutputStream();
- out.write("恭喜您,图片上传成功".getBytes());
- s.close();
- }
- catch(Exception e)
- {
- throw new RuntimeException("图片上传失败");
- }
- }
- }
- //服务端
- class TcpServer6
- {
- public static void main(String[] args)throws Exception
- {
- ServerSocket ss = new ServerSocket(9999);
- while(true)
- {
- Socket s = ss.accept();
- new Thread(new ClientThread(s)).start();
- }
- }
- }
- //客户端
- class TcpClient6
- {
- public static void main(String[] args) throws Exception
- {
- Socket s = new Socket("127.0.0.1",9999);
- FileInputStream fis = new FileInputStream("d:\\1.jpg");
- OutputStream out = s.getOutputStream();
- byte[] bufin = new byte[1024];
- int lenin = 0;
- while((lenin=fis.read(bufin))!=-1)
- {
- out.write(bufin,0,lenin);
- }
- s.shutdownOutput();
- InputStream in = s.getInputStream();
- byte[] bufout = new byte[1024];
- int lenout = in.read(bufout);
- String info = new String(bufout,0,lenout);
- System.out.println(info);
-
- s.close();
- }
- }
复制代码 问题是这样的,我把服务端开启后,用客户端给服务端发了几个图片,但是我发现我发到服务端的图片怎么都不能显示?我感觉我代码没写错,而且用的都是字节流,应该不存在刷新的问题吧,怎么发生这种问题,连续几个图片都是如此。
|
|