当前位置:网站首页>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 !!");
}边栏推荐
- Zero-Shot Image Retrieval(零样本跨模态检索)
- 【对比学习】Understanding the Behaviour of Contrastive Loss (CVPR‘21)
- JS数据类型以及相互转换
- 图神经网络用于推荐系统问题(IMP-GCN,LR-GCN)
- R语言ggplot2可视化:可视化散点图并为散点图中的部分数据点添加文本标签、使用ggrepel包的geom_text_repel函数避免数据点之间的标签互相重叠(为数据点标签添加线段、指定线段的角度
- 基于TCP/IP在同一局域网下的数据传输
- 【AI4Code】《InferCode: Self-Supervised Learning of Code Representations by Predicting Subtrees》ICSE‘21
- PL/SQL入门,非常详细的笔记
- Meta-learning(元学习与少样本学习)
- 已解决The JSP specification requires that an attribute name is preceded by whitespace
猜你喜欢
![[USB device design] - composite device, dual hid high-speed (64BYTE and 1024byte)](/img/ce/534834c53c72a53fd62ff72a1d3b39.png)
[USB device design] - composite device, dual hid high-speed (64BYTE and 1024byte)

Qin long, a technical expert of Alibaba cloud: a prerequisite for reliability assurance - how to carry out chaos engineering on the cloud

winddows 计划任务执行bat 执行PHP文件 失败的解决办法

selenium使用———安装、测试

Brpc source code analysis (V) -- detailed explanation of basic resource pool

Application and innovation of low code technology in logistics management

php curl post Length Required 错误设置header头

【AI4Code】《Contrastive Code Representation Learning》 (EMNLP 2021)

【AI4Code】《Pythia: AI-assisted Code Completion System》(KDD 2019)

Brpc source code analysis (VI) -- detailed explanation of basic socket
随机推荐
What is the global event bus?
Meta learning (meta learning and small sample learning)
[imx6ull notes] - a preliminary exploration of the underlying driver of the kernel
【图攻防】《Backdoor Attacks to Graph Neural Networks 》(SACMAT‘21)
PHP one server sends pictures to another. Curl post file_ get_ Contents save pictures
Classification parameter stack of JS common built-in object data types
【GCN-RS】Region or Global? A Principle for Negative Sampling in Graph-based Recommendation (TKDE‘22)
Multi label image classification
【Debias】Model-Agnostic Counterfactual Reasoning for Eliminating Popularity Bias in RS(KDD‘21)
【高并发】SimpleDateFormat类到底为啥不是线程安全的?(附六种解决方案,建议收藏)
微信公众号开发 入手
pycharm连接远程服务器ssh -u 报错:No such file or directory
Go 垃圾回收器指南
【GCN-RS】Learning Explicit User Interest Boundary for Recommendation (WWW‘22)
Functions in JS
Transformer变体(Sparse Transformer,Longformer,Switch Transformer)
投屏收费背后:爱奇艺季度盈利,优酷急了?
【AI4Code】《Unified Pre-training for Program Understanding and Generation》 NAACL 2021
[MySQL 17] installation exception: could not open file '/var/log/mysql/mysqld log‘ for error logging: Permission denied
Solutions to the failure of winddowns planning task execution bat to execute PHP files