当前位置:网站首页>Data transmission under the same LAN based on tcp/ip
Data transmission under the same LAN based on tcp/ip
2022-07-25 12:05:00 【0000ff Plaid Shirt】
1.TCP/IP Network programming
When developing web applications , Will meet Socket The concept . An application passes through a Socket To establish a remote connection , and Socket Through internal TCP/IP The protocol transmits data to the network .
TCP/IP It is the abbreviation of transmission control protocol and network protocol , It defines how devices connect to the Internet , And how data is transferred between them .TCP/IP It's not an agreement , It's an umbrella term for a family of agreements , It includes IP agreement 、ICMP agreement 、TCP agreement 、 as well as http、ftp、pop3 Agreements, etc , Network computers are interconnected by this protocol family .
2. The data transfer
Use Socket When programming the network , In essence, it is the network communication between two processes . One of the processes must act as the server side , It will actively listen to the port at a specified location , A column must act as a client , It must actively connect with the server IP Address and specified port , If the connection is successful , The server and client have successfully established a TCP agreement , Both parties can send and receive data at any time .
For the server side , its Socket Is specified IP Address and specified port number .
For clients , its Socket It's on the computer IP Address and a random port number assigned by the operating system .
3. Server side
Java The standard library provides ServerSocket To implement the specified IP Listening on the specified port of . The implementation procedure is as follows :
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(6666); // Listen on the specified port
System.out.println("server is running...");
// Use while Loop to keep the server in the receiving state
while (true) {
Socket sock = ss.accept();
// Use Socket Stream for network communication
// ...
System.out.println("connected from " + sock.getRemoteSocketAddress());
}
}
}It should be noted that :
(1) Use try-catch Block to throw an exception
(2) Use while Loop to keep the server in the receiving state .
(3) Be sure to specify the listening port on the server .
4. client
The client connects to the server through the following code , And be sure to specify the port of the server , Otherwise, data transmission will not be carried out correctly .
public class Client {
public static void main(String[] args) throws IOException {
// Connect to the specified server and port
Socket sock = new Socket("localhost", 6666);
// Use Socket Stream for network communication
// ...
// close
sock.close();
System.out.println("disconnected.");
}
}
5. The reference sample :( The server · Chat with clients on the same LAN )
Server side :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try (DatagramSocket socket = new DatagramSocket(8888)) {
DatagramPacket sendPacket = new DatagramPacket(new byte[1024], 1024,
new InetSocketAddress("192.168.254.177", 9999));
DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 1024);
while (true) {
socket.receive(receivePacket);
String receiveContent = new String(receivePacket.getData(), receivePacket.getOffset(),
receivePacket.getLength());
if (receiveContent.equals("over")) {
System.out.println(" The other party quit chatting ......");
break;
}
System.out.println(" It said " + receiveContent);
System.out.print(" You say? :");
String sendContent = input.nextLine();
sendPacket.setData(sendContent.getBytes());
socket.send(sendPacket);
if (sendContent.equals("over")) {
System.out.println(" You quit chatting ...");
return;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}client :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(true) {
try (Socket cilent = new Socket("192.168.254.159", 8888);
BufferedWriter writer = new BufferedWriter(new
OutputStreamWriter(cilent.getOutputStream()));
BufferedReader reader = new BufferedReader(new
InputStreamReader(cilent.getInputStream()))
) {
// Get console input
String question = input.nextLine();
if(question.equals("over")) {
break;
}
// Send a message to the server
writer.write(question);
writer.flush();
// Temporarily end this output
cilent.shutdownOutput();
// Get the answer from the server
String answer = reader.readLine();
System.out.println("【 client 】 Answer from the server " + answer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(" This chat is over !!");
}边栏推荐
- There is no sound output problem in the headphone jack on the front panel of MSI motherboard [solved]
- I advise those students who have just joined the work: if you want to enter the big factory, you must master these concurrent programming knowledge! Complete learning route!! (recommended Collection)
- Intelligent information retrieval(智能信息检索综述)
- JS中的数组
- 【GCN-RS】Learning Explicit User Interest Boundary for Recommendation (WWW‘22)
- 【AI4Code】《Unified Pre-training for Program Understanding and Generation》 NAACL 2021
- 【AI4Code最终章】AlphaCode:《Competition-Level Code Generation with AlphaCode》(DeepMind)
- Zero-Shot Image Retrieval(零样本跨模态检索)
- brpc源码解析(一)—— rpc服务添加以及服务器启动主要过程
- What is the difference between session and cookie?? Xiaobai came to tell you
猜你喜欢
![[multimodal] hit: hierarchical transformer with momentum contract for video text retrieval iccv 2021](/img/48/d5ec2b80cd949b359bcb0bcf08f4eb.png)
[multimodal] hit: hierarchical transformer with momentum contract for video text retrieval iccv 2021

【CTR】《Towards Universal Sequence Representation Learning for Recommender Systems》 (KDD‘22)

dirReader. Readentries compatibility issues. Exception error domexception

【GCN-RS】Region or Global? A Principle for Negative Sampling in Graph-based Recommendation (TKDE‘22)

【AI4Code】《Unified Pre-training for Program Understanding and Generation》 NAACL 2021

给生活加点惊喜,做创意生活的原型设计师丨编程挑战赛 x 选手分享
![[RS sampling] a gain tuning dynamic negative sampler for recommendation (WWW 2022)](/img/23/0901da44160ca685d2c694ae9a834b.png)
[RS sampling] a gain tuning dynamic negative sampler for recommendation (WWW 2022)

Zero-Shot Image Retrieval(零样本跨模态检索)
![[untitled]](/img/83/9b9a0de33d48f7d041acac8cfe5d6a.png)
[untitled]

【AI4Code】《Contrastive Code Representation Learning》 (EMNLP 2021)
随机推荐
brpc源码解析(一)—— rpc服务添加以及服务器启动主要过程
brpc源码解析(四)—— Bthread机制
已解决 Files‘ name is invalid or does not exist (1205)
对比学习的应用(LCGNN,VideoMoCo,GraphCL,XMC-GAN)
【GCN】《Adaptive Propagation Graph Convolutional Network》(TNNLS 2020)
What is the global event bus?
马斯克的“灵魂永生”:一半炒作,一半忽悠
30套中国风PPT/创意PPT模板
R语言ggplot2可视化:使用ggpubr包的ggstripchart函数可视化点状条带图、设置palette参数配置不同水平数据点的颜色、设置add参数在点状条带图中添加均值标准差竖线
[USB device design] - composite device, dual hid high-speed (64BYTE and 1024byte)
Web APIs(获取元素 事件基础 操作元素)
R语言ggpubr包ggarrange函数将多幅图像组合起来、annotate_figure函数为组合图像添加注释、注解、标注信息、fig.lab参数添加图像标签、fig.lab.face参数指定样式
【GCN-RS】Towards Representation Alignment and Uniformity in Collaborative Filtering (KDD‘22)
【对比学习】Understanding the Behaviour of Contrastive Loss (CVPR‘21)
异构图神经网络用于推荐系统问题(ACKRec,HFGN)
The applet image cannot display Base64 pictures. The solution is valid
winddows 计划任务执行bat 执行PHP文件 失败的解决办法
Power BI----这几个技能让报表更具“逼格“
What is the difference between session and cookie?? Xiaobai came to tell you
【GCN-RS】MCL: Mixed-Centric Loss for Collaborative Filtering (WWW‘22)