客户端:
关闭资源
1 package Demo1.JavaSe.javasocket;
2
3 import java.io.*;
4 import java.net.InetAddress;
5 import java.net.Socket;
6 import java.net.UnknownHostException;
7
8 //文件上传操作
9 public class JavaDemo2 {
10 //客户端
11 public static void main(String[] args) throws Exception {
12 //client----发送数据(输出流)------------(输入)-【管道流处理数据】-(输出)------接收数据(输入流)------server
13
14
15
16 // 1.创建Socket连接对象:创建它对应的对接的iP和端口。。。
17 Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9999);
18 //2.创建一个输出流
19 OutputStream outputStream = socket.getOutputStream();
20 //3.传入文件需要文件流
21 //读取文件
22 FileInputStream myFileStream = new FileInputStream(new File("src/a123.jpg"));
23 //写出文件
24 byte[] buffer = new byte[1024];
25 int len;
26 while ((len=myFileStream.read(buffer))!=-1){
27 outputStream.write(buffer,0,len);
28 }
29 //同知服务器我传输完成
30 socket.shutdownOutput();
31 System.out.println("上传成功");
32
33 //接受服务器发过来的
34 InputStream isput = socket.getInputStream();
35 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
36 byte[] buffer2 = new byte[1024];
37 int len2;
38 while ((len2=isput.read(buffer2))!=-1){
39 byteArrayOutputStream.write(buffer2,0,len2);
40 }
41 //打印服务端的确认消息
42 System.out.println(byteArrayOutputStream.toString());
43
44 //关闭资源
45 byteArrayOutputStream.close();
46 isput.close();
47
48 myFileStream.close();
49 outputStream.close();
50 socket.close();
51
52
53
54 }
55
56 }
服务器:
反馈给客户端消息,关闭
package Demo1.JavaSe.javasocket;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class JavaDemo2Server {
//服务端
public static void main(String[] args) throws IOException {
//1.创建服务。
ServerSocket serverSocket = new ServerSocket(9999);
//2.监听客户端消息
Socket accept = serverSocket.accept();//阻塞式监听
//3.获取输入流
InputStream iput = accept.getInputStream();
//4.文件输出
FileOutputStream receive = new FileOutputStream(new File("receive.jpg"));
byte[] buffer = new byte[1024];
int len;
//输入流 把信息读取到 缓冲区 返回字节数
while ((len = iput.read(buffer))!=-1){
receive.write(buffer,0,len);
}
System.out.println("接受成功"+len+"字节数");
//反馈给客户端
OutputStream outputStream = accept.getOutputStream();
outputStream.write("来自服务器的确认消息!".getBytes());
//5.关闭
receive.close();
iput.close();
serverSocket.close();
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章