基于聊天客户端的基础上的文件(txt文件)传输
客户端代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class uploadclient {
public static void main(string[] args) throws unknownhostexception, ioexception {
// todo auto-generated method stub
//1,创建socket客户端对象
socket s = new socket( "localhost" , 10005 );
//2,读取本地文件
bufferedreader bufr = new bufferedreader( new filereader( "c:\\新建文件夹\\client.txt" ));
//3,socket流
printwriter out = new printwriter(s.getoutputstream(), true );
string line = null ;
while ((line=bufr.readline())!= null ){
out.println(line);
}
//告诉服务端,客户端写完了
s.shutdownoutput();
//4,读取服务端返回的上传成功对象
bufferedreader bufin = new bufferedreader( new inputstreamreader(s.getinputstream()));
string str = bufin.readline();
system.out.println(str);
//关闭资源
bufr.close();
s.close();
}
}
|
服务端代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public static void main(string[] args) throws unknownhostexception, ioexception {
// todo auto-generated method stub
//1,
serversocket ss = new serversocket( 10005 );
//2,获取socket对象
socket s = ss.accept();
//获取ip
system.out.println(s.getinetaddress().gethostaddress()+ "....conected" );
//3,获取socket读取流,并装饰
bufferedreader bufin = new bufferedreader( new inputstreamreader(s.getinputstream()));
//4,写入文件
bufferedwriter bufw = new bufferedwriter( new filewriter( "c:\\新建文件夹\\server.txt" ));
string line = null ;
while ((line=bufin.readline())!= null ){
bufw.write(line);
bufw.newline(); //换行
bufw.flush(); //刷新流
}
printwriter out = new printwriter(s.getoutputstream(), true );
out.println( "上传成功" );
bufw.close();
s.close(); //关闭客户端
ss.close(); //关闭服务端
}
|
要注意的是tcp传输中,一定要先运行服务端再运行客户端。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接
原文链接:https://blog.csdn.net/lzq1326253299/article/details/86526556