本帖最后由 杨浩 于 2013-1-28 16:38 编辑
- package tcpdemo;
- import java.io.IOException;
- import java.net.*;
- public class UploadPicServer {
- public static void main(String[] args) throws IOException {
- ServerSocket ss = new ServerSocket(10001);
- while(true){
- Socket s = ss.accept();
- new Thread(new UploadTask(s)).start();
- }
- //ss.close();
- }
- }
复制代码- package tcpdemo;
- import java.io.*;
- import java.net.*;
- public class UploadTask implements Runnable {
- private Socket s;
- public UploadTask(Socket s){
- this.s = s;
- }
- public void run(){
- int count = 0;
- String ip = s.getInetAddress().getHostAddress();
- try{
- InputStream in = s.getInputStream();
- File dir = new File("png");
- if(!(dir.exists())){
- dir.mkdirs();
- }
- File file = new File(dir,ip+".png");
- while(file.exists()){
- file = new File(dir,ip+"("+(++count)+").png");
- }
- FileOutputStream fops = new FileOutputStream(file);
- byte[] buf = new byte[1024];
- int len = 0;
- while ((len=in.read(buf))!=-1){
- fops.write(buf, 0, len);
- }
- OutputStream out = s.getOutputStream();
- out.write("传输完毕!".getBytes());
- fops.close();
- s.close();
- }catch(Exception e){
- System.out.println("ERROR!");
- }
- }
- }
复制代码- package tcpdemo;
- import java.io.*;
- import java.net.*;
- public class UploadPicClient {
- public static void main(String[] args) throws Exception {
- Socket s = new Socket("192.168.0.100",10001);
- InputStream in = s.getInputStream();
- OutputStream out = s.getOutputStream();
- File file = new File("1.png");
- FileInputStream fins = new FileInputStream(file);
- byte[] buf = new byte[1024];
- int len = 0;
- while((len=fins.read(buf))!=-1){
- out.write(buf, 0, buf.length);
- }
- s.shutdownOutput();
- byte[] bufin = new byte[1024];
- in.read(bufin);
- System.out.println(new String(bufin,0,bufin.length));
- fins.close();
- s.close();
- }
- }
复制代码 服务端接收到的图片,大小会变化,而如果把服务端接收到的图片当作源的话,那么就一样大了...
难道是因为文件末尾多了字符么?
|
|