网络编程【九】Tcp 图片的上传

2019-04-15 13:50发布

图片的上传服务器操作练习。
客户端把d:picwelcome.jpg 这张图片图片上传到服务器。服务器收到图片后把存片存在:"d:dataserver.jpg",并给客户端返回:“上传成功”。注意,这里用的是字节流。


客户端:


import java.net.*;
import java.io.*;
public class TcpClient {

public static void main(String[] args)throws Exception {
Socket s = new Socket("192.168.0.124",10006);
FileInputStream fis = new FileInputStream("d:\pic\welcome.jpg");
OutputStream out = s.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len=fis.read(buf))!=-1){
out.write(buf,0,len);
}
s.shutdownOutput();

InputStream in = s.getInputStream();
byte[] bufIn = new byte[1024];
int number = in.read(bufIn);
System.out.println(new String(bufIn,0,number));

fis.close();
s.close();





}

}





服务端:

import java.net.*;
import java.io.*;
class TcpServer {

public static void main(String[] args)throws Exception {
ServerSocket ss = new ServerSocket(10006);
Socket s = ss.accept();

String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"---> connect");

FileOutputStream fos = new FileOutputStream("d:\data\server.jpg");
InputStream in = s.getInputStream();

byte[] buf = new byte[1024];
int len = 0;
while((len=in.read(buf))!=-1){
fos.write(buf,0,len);
}

OutputStream out = s.getOutputStream();
out.write("上传成功".getBytes());

fos.close();
s.close();
ss.close();





out.close();
s.close();
ss.close();

}

}