题目
客户端:将本地文件上传到服务器,接收服务器的反馈 服务端:接收客户端上传的文件,上传完毕之后给出反馈
代码实战
1、客户端代码
package com. heima ;
import java. io. * ;
import java. net. Socket ;
public class Client {
public static void main ( String [ ] args) throws IOException {
Socket socket = new Socket ( "127.0.0.1" , 10000 ) ;
BufferedInputStream bis = new BufferedInputStream ( new FileInputStream ( "G:\\wjkwk\\clientdir\\123.jpg" ) ) ;
BufferedOutputStream bos = new BufferedOutputStream ( socket. getOutputStream ( ) ) ;
byte [ ] bytes = new byte [ 1024 ] ;
int len;
while ( ( len = bis. read ( bytes) ) != - 1 ) {
bos. write ( bytes, 0 , len) ;
}
socket. shutdownOutput ( ) ;
BufferedReader br = new BufferedReader ( new InputStreamReader ( socket. getInputStream ( ) ) ) ;
String line = br. readLine ( ) ;
System . out. println ( line) ;
socket. close ( ) ;
}
}
2、服务端代码
package com. heima ;
import java. io. * ;
import java. net. ServerSocket ;
import java. net. Socket ;
import java. util. UUID ;
public class Server {
public static void main ( String [ ] args) throws IOException {
ServerSocket serverSocket = new ServerSocket ( 10000 ) ;
Socket socket = serverSocket. accept ( ) ;
BufferedInputStream bis = new BufferedInputStream ( socket. getInputStream ( ) ) ;
String name = UUID . randomUUID ( ) . toString ( ) . replace ( "-" , "" ) ;
BufferedOutputStream bos = new BufferedOutputStream ( new FileOutputStream ( "G:\\wjkwk\\serverdir\\" + name+ ".jpg" ) ) ;
int len;
byte [ ] bytes = new byte [ 1024 ] ;
while ( ( len = bis. read ( bytes) ) != - 1 ) {
bos. write ( bytes, 0 , len) ;
}
BufferedWriter bw = new BufferedWriter ( new OutputStreamWriter ( socket. getOutputStream ( ) ) ) ;
bw. write ( "上传成功" ) ;
bw. newLine ( ) ;
bw. flush ( ) ;
socket. close ( ) ;
serverSocket. close ( ) ;
}
}
3、运行结果