当前位置:网站首页>Socket class understanding and learning about TCP character stream programming
Socket class understanding and learning about TCP character stream programming
2022-07-28 13:53:00 【Daxiong who loves learning】
List of articles
Basic introduction
Socket (socket): Is the cornerstone of communication , It's supporting TCP/IP Basic operation unit of network communication of protocol . It is an abstract representation of the endpoint in the process of network communication , Contains five kinds of information necessary for network communication : The protocol used for the connection , localhost IP Address , Protocol port of local process , Remote host's IP Address , Protocol port of remote process
- socket Is the cornerstone of communication , It's supporting TCP/IP Basic operation unit of network communication of protocol .
- socket To put it simply , from port , agreement , Address three components .
- The connection process between sockets is divided into three steps : Server listening , Client request , Connect to confirm .
- Because usually Socket The connection is TCP Connect , therefore Socket Once the connection is established , Both sides of the communication can start sending data content to each other , Until both sides are disconnected .
- But in actual network applications , Communication between client and server often needs to go through multiple intermediate nodes , For example, router 、 gateway 、 Firewall, etc , Most firewalls default to closing connections that are inactive for a long time Socket The connection is broken , So you need to tell the network by polling , The connection is active .
Socket It is mainly used to develop network applications , Its back is widely used
Both ends of the communication need Socket, It is the breakpoint of communication between two machines
Network communication is actually Socket Communication for
Socket Allows programs to treat network connections as a stream , The data is in two Socket Interpass IO transmission
commonly The application that initiates communication actively belongs to the client , The server waiting for the communication request
Sketch Map :

Code implementation
Be sure to pay attention to , You must first open the server , Starting the client , Otherwise, an error will be reported
** Be careful :** The code examples here are all about sending and receiving information , If you need to send or receive pictures, it's almost the same , Only byte stream must be used instead of character stream , The basic process is to use IO Knowledge in .
demand 1:
- Write a server and a client
- The service side in 9999 Port listening
- Client connects to server , send out "hello,server", sign out
- The server receives the information sent by the client and outputs , sign out
Server side
/** * * Server side * demand : Receive the information sent from the client and output * * @author: Lei Zijie * @date:2022/7/27 */
public class ScoketTCP01Server {
public static void main(String[] args) throws IOException {
// newly build serverSocket object , Realization 9999 Port listening
ServerSocket serverSocket = new ServerSocket(9999);
// The pipeline will be generated after the client connects
Socket socket = serverSocket.accept();
// Get the input stream of the pipeline
InputStream inputStream = socket.getInputStream();
byte[] buf=new byte[1024];
int len = 0;
while ((len = inputStream.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
// Closed flow
inputStream.close();
socket.close();
serverSocket.close();
}
}
client
After the output stream writes data, it must be flush(), At the same time, mark the end
/** * * client * demand : Send a message to the server * * @author: Lei Zijie * @date:2022/7/27 */
public class ScoketTCP01Client {
public static void main(String[] args) throws IOException {
// obtain socket Connect
Socket socket = new Socket(InetAddress.getLocalHost(),9999);
// Get output stream object
OutputStream outputStream = socket.getOutputStream();
// Write information to the output stream
outputStream.write("hello,server".getBytes());
// Closed flow
outputStream.close();
socket.close();
}
}
test result
The server receives the message

demand 2
- Write a server and a client
- The service side in 9999 Port listening
- Client connects to server , send out "hello,server", And receive the data sent back by the server "hello,client", sign out
- The server receives the information output sent by the client , And send the "hello,client", sign out
Server side
After the output stream writes data, it must be flush(), At the same time, mark the end
/** * * Server side * demand : Receive the information output sent from the client , And return a message to the client * * * @author: Lei Zijie * @date:2022/7/27 */
public class ScoketTCP02Server {
public static void main(String[] args) throws IOException {
// newly build serverSocket object , Realization 9999 Port listening
ServerSocket serverSocket = new ServerSocket(9999);
// The pipeline will be generated after the client connects
Socket socket = serverSocket.accept();
// Get the input stream of the pipeline , Get the information sent by the client
InputStream inputStream = socket.getInputStream();
byte[] buf=new byte[1024];
int len = 0;
while ((len = inputStream.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
// Close the read
socket.shutdownInput();
// Get output stream object
OutputStream outputStream = socket.getOutputStream();
// Write information to the output stream , Send it to the server
outputStream.write("hello,client".getBytes());
// Close the write
socket.shutdownOutput();
// Closed flow
outputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}
client
After the output stream writes data, it must be flush(), At the same time, mark the end
/** * * client * demand : Send a message to the server , And receive a message returned from the server * * @author: Lei Zijie * @date:2022/7/27 */
public class ScoketTCP02Client {
public static void main(String[] args) throws IOException {
// obtain socket Connect
Socket socket = new Socket(InetAddress.getLocalHost(),9999);
// Get output stream object
OutputStream outputStream = socket.getOutputStream();
// Write information to the output stream , Send it to the server
outputStream.write("hello,server".getBytes());
// Close the write
socket.shutdownOutput();
// Get the input stream of the pipeline , Get the information sent by the server
InputStream inputStream = socket.getInputStream();
byte[] buf=new byte[1024];
int len = 0;
while ((len = inputStream.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
// Closed flow
inputStream.close();
outputStream.close();
socket.close();
}
}
test result
The server receives the message

Client receives message

demand 3
Use character stream to complete , The previous two requirements are completed by using byte stream
- Write a server and a client
- The service side in 9999 Port listening
- Client connects to server , send out "hello,server", And receive the data sent back by the server "hello,client", sign out
- The server receives the information output sent by the client , And send the "hello,client", sign out
Server side
After the output stream writes data, it must be flush(), At the same time, mark the end
/** * * Server side * demand : Use character stream , Receive the information output sent from the client , And return a message to the client * * @author: Lei Zijie * @date:2022/7/27 */
public class ScoketTCP03Server {
public static void main(String[] args) throws IOException {
// newly build serverSocket object , Realization 9999 Port listening
ServerSocket serverSocket = new ServerSocket(9999);
// The pipeline will be generated after the client connects
Socket socket = serverSocket.accept();
// Get the input stream of the pipeline , Get the information sent by the client
InputStream inputStream = socket.getInputStream();
// Transfer byte stream input to character stream input
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
char[] cbuf=new char[1024];
int len;
while ((len = inputStreamReader.read(cbuf))!=-1){
System.out.println(new String(cbuf,0,len));
}
// Close the read
socket.shutdownInput();
// Get output stream object
OutputStream outputStream = socket.getOutputStream();
// Convert byte stream output stream to character stream output stream
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
// Write information to the output stream , Send it to the server
outputStreamWriter.write("hello,client");
// You need to brush a new stream before writing
outputStreamWriter.flush();
// Close the write
socket.shutdownOutput();
// Closed flow
outputStreamWriter.close();
inputStreamReader.close();
socket.close();
serverSocket.close();
}
}
client
After the output stream writes data, it must be flush(), At the same time, mark the end
/** * * client * demand : Use character stream , Send a message to the server , And receive a message returned from the server * * @author: Lei Zijie * @date:2022/7/27 */
public class ScoketTCP03Client {
public static void main(String[] args) throws IOException {
// obtain socket Connect
Socket socket = new Socket(InetAddress.getLocalHost(),9999);
// Get output stream object
OutputStream outputStream = socket.getOutputStream();
// Convert byte stream output stream to character stream output stream
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
// Write information to the output stream , Send it to the server
outputStreamWriter.write("hello,server");
// You need to brush a new stream before writing
outputStreamWriter.flush();
// Close the write
socket.shutdownOutput();
// Get the input stream of the pipeline , Get the information sent by the server
InputStream inputStream = socket.getInputStream();
// Transfer byte stream input to character stream input
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
char[] cbuf=new char[1024];
int len;
while ((len = inputStreamReader.read(cbuf))!=-1){
System.out.println(new String(cbuf,0,len));
}
// Closed flow
inputStreamReader.close();
outputStreamWriter.close();
socket.close();
}
}
test result
The server receives the message

Client receives message

Send pictures 、 Video and other documents process description
Because it's a picture 、 Video and other documents , So we must use byte stream for transmission
demand :
- Write a server and a client
- The service side in 8888 Port listening
- The client connects to the server , Send a local picture
- The server receives the picture sent by the client , Save to src Next , send out “ Received the picture ” To the client , And then quit
- The client receives the “ Received the picture ”, And then quit
Process example :
- The client uses the byte input stream to input the pictures in the disk into the memory
- The client uses the byte output stream to output the pictures in memory to the server
- The server uses the byte input stream to obtain the pictures in the client byte output stream
- The server uses byte output stream to output pictures to disk file
Server side
After the output stream writes data, it must be flush(), At the same time, mark the end
/** * * Server side * * @author: Lei Zijie * @date:2022/7/27 */
public class TCPFileUploadServer {
public static void main(String[] args) throws IOException {
// monitor 8888 port
ServerSocket serverSocket = new ServerSocket(8888);
// Waiting for the connection
Socket socket = serverSocket.accept();
BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
// Created byte stream output stream
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("basic_review\\src\\socket_\\ picture .jpg"));
// Read picture information
byte[] buf = new byte[1024];
int len;
while ((len = bufferedInputStream.read(buf)) != -1){
bufferedOutputStream.write(buf,0,len);
}
bufferedOutputStream.flush();
socket.shutdownInput();
bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
bufferedOutputStream.write(" Received the picture ".getBytes());
// Refresh stream
bufferedOutputStream.flush();
socket.shutdownOutput();
bufferedOutputStream.close();
bufferedInputStream.close();
socket.close();
serverSocket.close();
}
}
client
After the output stream writes data, it must be flush(), At the same time, mark the end
/** * * client * * @author: Lei Zijie * @date:2022/7/27 */
public class TCPFileUploadClient {
public static void main(String[] args) throws IOException {
// Connect to the host 8888 port , obtain socket object
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
// Read file address
String filePath ="f:\\ssm The blog system .jpg";
// Created byte stream input stream
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));
// Created byte stream output stream
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
// Read picture information
byte[] buf = new byte[1024];
int len;
while ((len = bufferedInputStream.read(buf)) != -1){
// Write to pipeline
bufferedOutputStream.write(buf,0,len);
}
// Refresh stream
bufferedOutputStream.flush();
// Close write
socket.shutdownOutput();
bufferedInputStream = new BufferedInputStream(socket.getInputStream());
while ((len = bufferedInputStream.read(buf)) != -1){
System.out.println(new String(buf,0,len));
}
socket.shutdownInput();
bufferedOutputStream.close();
bufferedInputStream.close();
socket.close();
}
}
summary
Current review java The basic review has reached the stage of computer network , I found myself lack of knowledge in network communication programming , This article is used to record learning java Network programming technology
Another point !!!!! After using the output stream to write data, be sure to flush(), At the same time, mark the end , Otherwise you may report an error
边栏推荐
- IntersectionObserver交叉观察器
- 111. SAP UI5 FileUploader 控件实现本地文件上传,接收服务器端的响应时遇到跨域访问错误
- 【飞控开发基础教程7】疯壳·开源编队无人机-SPI(气压计数据获取)
- Strict mode -- let and const -- arrow function -- Deconstruction assignment -- string template symbol -- set and map -- generator function
- Excellent performance! Oxford, Shanghai, AI Lab, Hong Kong University, Shangtang, and Tsinghua have joined forces to propose a language aware visual transformer for reference image segmentation! Open
- R language uses dpois function to generate Poisson distribution density data and plot function to visualize Poisson distribution density data
- SAP UI5 FileUploader 控件实现本地文件上传,接收服务器端的响应时遇到跨域访问错误的试读版
- POJ3268最短路径题解
- 产品经理:岗位职责表
- 数据库系统原理与应用教程(062)—— MySQL 练习题:操作题 32-38(六)
猜你喜欢

30天刷题计划(二)

DDoS protection with iptables
![[security] read rfc6749 and understand the authorization code mode under oauth2.0](/img/dc/e6d8626195b2e09a6c06050a9b552e.jpg)
[security] read rfc6749 and understand the authorization code mode under oauth2.0

111. SAP UI5 FileUploader 控件实现本地文件上传,接收服务器端的响应时遇到跨域访问错误

国产API管理工具Eolink太好用了,打造高效的研发利器

Today's sleep quality record 75 points

Some thoughts on.Net desktop development

30 day question brushing plan (II)

最强分布式锁工具:Redisson

酷炫操作预热!代码实现小星球特效
随机推荐
R language uses LM function to build multiple linear regression model, writes regression equation according to model coefficient, and uses conflict function to give 95% confidence interval of regressi
C language: random generated number + merge sort
性能超群!牛津&上海AI Lab&港大&商汤&清华强强联手,提出用于引用图像分割的语言感知视觉Transformer!代码已开源...
Continuous (integration -- & gt; delivery -- & gt; deployment)
掌握常见的几种排序-选择排序
Poj3268 shortest path solution
What is the reason why the words behind word disappear when typing? How to solve it?
UVA1599理想路径题解
Denial of service DDoS Attacks
Beyond istio OSS -- current situation and future of istio Service Grid
vite在项目中配置路径别名
要想组建敏捷团队,这些方法不可少
leetcode-深度优先与广度优先遍历
Cool operation preheating! Code to achieve small planet effect
R语言使用lm函数构建线性回归模型、使用subset函数指定对于数据集的子集构建回归模型(使用floor函数和length函数选择数据前部分构建回归模型)
在 Kubernetes 中部署应用交付服务(第 1 部分)
Excellent performance! Oxford, Shanghai, AI Lab, Hong Kong University, Shangtang, and Tsinghua have joined forces to propose a language aware visual transformer for reference image segmentation! Open
Children's programming electronic society graphical programming level examination scratch Level 2 real problem analysis (judgment question) June 2022
To build agile teams, these methods are indispensable
I miss the year of "losing" Li Ziqi