当前位置:网站首页>基于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("本次聊天结束!!");
}边栏推荐
- Job interviews are always a second kill? After reading the seckill system notes secretly stored by JD T8, I have given my knees
- brpc源码解析(七)—— worker基于ParkingLot的bthread调度
- 擎创科技加入龙蜥社区,共建智能运维平台新生态
- WIZnet嵌入式以太网技术培训公开课(免费!!!)
- session和cookie有什么区别??小白来告诉你
- cookie and session
- 【mysql学习09】
- W5500 adjusts the brightness of LED light band through upper computer control
- php 一台服务器传图片到另一台上 curl post file_get_contents保存图片
- WIZnet W5500系列培训活动之“MQTT协议讲解和实践(接入OneNET)”
猜你喜欢

Review in the middle of 2022 | understand the latest progress of pre training model

油猴脚本链接

Risks in software testing phase

JS运算符

第一个C语言程序(从Hello World开始)

Functions in JS

软件缺陷的管理

brpc源码解析(一)—— rpc服务添加以及服务器启动主要过程

W5500 is in TCP_ In server mode, you cannot Ping or communicate in the switch / router network.

软件测试阶段的风险
随机推荐
Dynamic planning question 05_ Missile interception
基于Caffe ResNet-50网络实现图片分类(仅推理)的实验复现
[leetcode brush questions]
[MySQL learning 09]
硬件外设=maixpy3
Javescript loop
如何解决“W5500芯片在TCP_Client模式下,断电重启之后无法立即连接到服务器”的问题
Plot ==pyqt5
Similarity matrix, diagonalization condition
W5500多节点连接
【leetcode刷题】
php 一台服务器传图片到另一台上 curl post file_get_contents保存图片
奉劝那些刚参加工作的学弟学妹们:要想进大厂,这些并发编程知识是你必须要掌握的!完整学习路线!!(建议收藏)
winddows 计划任务执行bat 执行PHP文件 失败的解决办法
brpc源码解析(二)—— brpc收到请求的处理过程
【mysql学习08】
A beautiful gift for girls from programmers, H5 cube, beautiful, exquisite, HD
Greedy problem 01_ Activity arrangement problem
The JSP specification requires that an attribute name is preceded by whitespace
Flinksql client connection Kafka select * from table has no data error, how to solve it?