Java网络通信

时间:2023-03-08 21:06:58

一、基本概念

1.网络程序:

能够接受另一台计算机发送过来的数据或者能够向另一台计算机发送数据的程序叫做网络程序。

2.IP

能够在网络中唯一标示一台主机的编号就是IP

3.端口号

16位数字表示

4.协议

进行网络中数据交换(通信)而建立的规则、标准或者约定。

分类:TCP:面相连接的可靠的传输的连接,类似打电话

UDP:是无连接的不可靠的传输协议,类似写信

二、套接字Socket

1.基于UDP的Socket编程

步骤:1.定义码头  Datagram Socket对象ds

2.定义可以用来接受或发送数据的集装箱     DatagramPacket对象dp

3.在码头上用集装箱接收对方发来的数据ds.receive(dp))

或者在码头上把集装箱的数据发送给对方ds.send(dp))

4.关闭码头    ds.close()

基于UDP的socket编程实例——服务器与客户端之间的通信

服务器端

package UDPsocketTest;
import java.net.*;
import java.io.*; //UDP的服务器端
public class TestUDPServer {
public static void main(String[] args)throws Exception{
DatagramSocket ds=new DatagramSocket(5678);//5678是端口号
byte buf[]=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf,buf.length);
try{
while(true){
ds.receive(dp);
//从集装箱中取出对方放松过来的数据
ByteArrayInputStream bais=new ByteArrayInputStream(dp.getData());
DataInputStream dis=new DataInputStream(bais);
System.out.println(ds.readLong());
}
}
catch(Exception e){
e.printStackTrace();
ds.close();
}
}
}

客户端

package UDPsocketTest;
import java.net.*;
import java.io.*; //服务器端
public class TestUDPClient {
public static void main(String[] args) throws Exception{
DatagramSocket ds=new DatagramSocket();
long n=1000L;
ByteArrayOutputStream baos=new ByteArrayOutputStream();
DataOutputStream daos=new DataOutputStream(baos);
daos.writeLong(n);
byte[] buf=baos.toByteArray();
DatagramPacket dp=new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",5678));
ds.send(dp);
ds.close();
}
}