当前位置:网站首页>基于TCP/IP在同一局域网下的数据传输
基于TCP/IP在同一局域网下的数据传输
2022-07-25 11:07:00 【#0000FF格子衫】
1.TCP/IP网络编程
在开发网络应用程序的时候,会遇到Socket这个概念。一个应用程序通过一个Socket来建立远程连接,而Socket内部通过TCP/IP协议把数据传输到网络。
TCP/IP是传输控制协议和网络协议的简称,它定义设备如何连入因特网,以及数据如何在他们之间传输的标准。TCP/IP不是一个协议,而是一个协议族的统称,里面包括了IP协议、ICMP协议、TCP协议、以及http、ftp、pop3协议等,网络计算机都采用这套协议族进行互联。
2.数据传输
使用Socket进行网络编程时,本质上就是进行俩个进程之间的网络通信。其中一个进程必须充当服务器端,它会主动去监听某个指定位置的端口,列一个必须充当客户端,它必须主动与连接服务器端的IP地址和指定端口,如果连接成功,服务器端与客户端就成功的建立了一个TCP协议,双方后续就可以随时发送和接收数据。
对服务器端来说,它的Socket是指定的IP地址和指定的端口号。
对客户端来说,它的Socket是它所在的计算机的IP地址和一个操作系统分配的随机端口号。
3.服务器端
Java标准库提供了ServerSocket来实现对指定IP的指定端口的监听。实现程序如下:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(6666); // 监听指定端口
System.out.println("server is running...");
//使用while循环来让服务器一直保持接收的状态
while (true) {
Socket sock = ss.accept();
// 使用Socket流进行网络通信
// ...
System.out.println("connected from " + sock.getRemoteSocketAddress());
}
}
}需要注意的是:
(1)使用try-catch块来抛出异常
(2)使用while循环来让服务器一直保持接收状态。
(3)一定要指定服务器端的监听端口。
4.客户端
客户端通过如下代码来连接到服务器端,而且一定要指定服务器的端口,否则会无法正确的进行数据传输。
public class Client {
public static void main(String[] args) throws IOException {
// 连接指定服务器和端口
Socket sock = new Socket("localhost", 6666);
// 使用Socket流进行网络通信
// ...
// 关闭
sock.close();
System.out.println("disconnected.");
}
}
5.参考示例:(服务器·与客户端在同一局域网下的聊天)
服务器端:
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("对方退出聊天......");
break;
}
System.out.println("它说" + receiveContent);
System.out.print("你说:");
String sendContent = input.nextLine();
sendPacket.setData(sendContent.getBytes());
socket.send(sendPacket);
if (sendContent.equals("over")) {
System.out.println("你退出聊天...");
return;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}客户端:
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()))
) {
//获取控制台的输入
String question = input.nextLine();
if(question.equals("over")) {
break;
}
// 发送消息至服务器
writer.write(question);
writer.flush();
//暂时结束本次输出
cilent.shutdownOutput();
//获取来自服务器的回答
String answer = reader.readLine();
System.out.println("【客户端】来自服务器的回答" + answer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("本次聊天结束!!");
}边栏推荐
- 绘图==PYQT5
- 【高并发】高并发场景下一种比读写锁更快的锁,看完我彻底折服了!!(建议收藏)
- JS作用域以及预解析
- 动态规划问题03_最大子段和
- Various controls ==pyqt5
- Signal and slot mechanism ==pyqt5
- 各种控件==PYQT5
- Summary of combination problems of Li Kou brush questions (backtracking)
- Small program of vegetable distribution in community
- The principle analysis of filter to solve the request parameter garbled code
猜你喜欢

Functions in JS

【USB设备设计】--复合设备,双HID高速(64Byte 和 1024Byte)

油猴脚本链接

Onenet platform control w5500 development board LED light

软件缺陷的管理

第一个C语言程序(从Hello World开始)
![[MySQL learning 09]](/img/27/2578f320789ed32552d6f69f14a151.png)
[MySQL learning 09]

What is the global event bus?

Varest blueprint settings JSON
![[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)
随机推荐
【USB设备设计】--复合设备,双HID高速(64Byte 和 1024Byte)
Introduction to shortcut keys in debug chapter
Oracle parsing XML with the same name
Make a reliable delay queue with redis
【高并发】SimpleDateFormat类到底为啥不是线程安全的?(附六种解决方案,建议收藏)
Plot ==pyqt5
LeetCode 50. Pow(x,n)
【MySQL 17】安装异常:Could not open file ‘/var/log/mysql/mysqld.log‘ for error logging: Permission denied
SQL language (V)
Signal and slot mechanism ==pyqt5
Objects in JS
[imx6ull notes] - a preliminary exploration of the underlying driver of the kernel
W5500在处于TCP_Server模式下,在交换机/路由器网络中无法ping通也无法通讯。
【高并发】高并发场景下一种比读写锁更快的锁,看完我彻底折服了!!(建议收藏)
11. Reading rumors spread with deep learning
小程序image 无法显示base64 图片 解决办法 有效
W5500 multi node connection
布局管理==PYQT5
Learn NLP with Transformer (Chapter 1)
Brpc source code analysis (VI) -- detailed explanation of basic socket