0%

TCP网络编程

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.sympa.lesson01;

import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class InetAddressTest {

@Test
public void client(){
Socket socket = null;
OutputStream os = null;
FileInputStream fis = null;
try{
//1. 创建Socket对象,指明服务器端IP和端口号
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet, 8888);
//2.获取输出流,用于输出数据
os = socket.getOutputStream();
fis = new FileInputStream(new File("F:\\jdbc\\src\\com\\sympa\\lesson01\\01.jpg"));
byte[] car = new byte[1024];
int len = 0;
//3.写出数据
while((len = fis.read(car)) != -1){
os.write(car, 0, len);
}
socket.shutdownOutput();

InputStream is = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] car1 = new byte[20];
while((len = is.read(car1)) != -1){
baos.write(car1, 0, len);
}
System.out.println(baos.toString());
} catch(IOException e) {
e.printStackTrace();
} finally {
try{
if(socket != null) socket.close();
if(os != null) os.close();
} catch (IOException e){
e.printStackTrace();
}
}
}

@Test
public void server() {
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
try{
//1.创建服务器端socket对象,指明自己端口号
ss = new ServerSocket(8888);
//2.表明可以接受来自于客户端的socket
socket = ss.accept();
//3.获取输入流
is = socket.getInputStream();
fos = new FileOutputStream("04.jpg");
byte[] buffer = new byte[1024];
int len;
//4.读取输入流数据
while((len = is.read(buffer)) != -1){
fos.write(buffer, 0, len);
}
socket.shutdownInput();
System.out.println("收到了来自于" + socket.getInetAddress().getHostAddress() + "的消息");

OutputStream os = socket.getOutputStream();
os.write("收到".getBytes(StandardCharsets.UTF_8));
} catch (IOException e){
e.printStackTrace();
} finally {
try{
if(fos != null) fos.close();
if(is != null) is.close();
if(socket != null) socket.close();
if(ss != null) ss.close();
} catch (IOException e){
e.printStackTrace();
}
}
}

}
------ THEEND ------

欢迎关注我的其它发布渠道