1.客户端代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public class uploadpicclient {
public static void main(string[] args) throws unknownhostexception, ioexception {
// todo auto-generated method stub
//1,创建客户端socket
socket s = new socket( "localhost" , 10088 );
//2,读取客户端要上传的图片文件
fileinputstream fis = new fileinputstream( "d:\\workspace\\day2019.1.17\\lanjing.jpg" );
//3,获取socket输出流,将读到的图片的数据发送到服务端
outputstream out = s.getoutputstream();
byte [] buf = new byte [ 1021 ];
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 lenin = in.read(buf);
string text = new string (buf, 0 ,lenin);
system.out.println(text);
//关闭资源
fis.close();
s.close();
}
}
|
2.服务端代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public class uploadpicsever {
public static void main(string[] args) throws ioexception {
// todo auto-generated method stub
//创建tcp的socket服务端
serversocket ss = new serversocket( 10088 );
//获取客户端
socket s = ss.accept();
string ip = s.getinetaddress().gethostaddress();
system.out.println(ip+ ".....connected" );
//读取客户端发来的数据
inputstream in = s.getinputstream();
//将读取到的数据存储到一个文件中。
file dir = new file( "d:\\workspace\\day2019.1.17" );
if (!dir.exists()){
dir.mkdirs();
}
file file = new file(dir, "blue.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);
}
//获取socket输出流,将上传成功字样发送给客户端
outputstream out = s.getoutputstream();
out.write( "上传成功" .getbytes());
fos.close();
s.close();
ss.close();
}
|
上传后和上传前的图片:
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接
原文链接:https://blog.csdn.net/lzq1326253299/article/details/86528524