1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
class UdpSend{ public static void main(String[] args) throws Exception{ //1,创建udp服务。通过DatagramSocket对象。 DatagramSocket ds = new DatagramSocket( 8888 ); //2,确定数据,并封装成数据包。 byte [] buf = "udp ge men lai le " .getBytes(); DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName( "222.195.152.1" ), 5000 ); //3,通过socket服务,将已有的数据包发送出去。通过send方法。 ds.send(dp); //4,关闭资源。 ds.close(); } } class UdpReceive{ public static void main(String[] args) throws Exception { //1,创建udp socket,建立端点。 DatagramSocket ds = new DatagramSocket( 5000 ); while ( true ) { //2,定义数据包。用于存储数据。 byte [] buf = new byte [ 1024 ]; DatagramPacket dp = new DatagramPacket(buf,buf.length); //3,通过服务的receive方法将收到数据存入数据包中。 ds.receive(dp); //阻塞式方法。 //4,通过数据包的方法获取其中的数据。 String ip = dp.getAddress().getHostAddress(); String data = new String(dp.getData(), 0 ,dp.getLength()); int port = dp.getPort(); System.out.println(ip+ ":" +data+ ":" +port); } //5,关闭资源 //ds.close(); } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import java.io.*; import java.net.*; class TcpClient{ public static void main(String[] args) throws Exception { //创建客户端的socket服务。指定目的主机和端口 Socket s = new Socket( "222.195.152.1" , 5001 ); //为了发送数据,应该获取socket流中的输出流。 OutputStream out = s.getOutputStream(); out.write( "test tcp communication" .getBytes()); s.close(); } } class TcpServer{ public static void main(String[] args) throws Exception{ //建立服务端socket服务。并监听一个端口。 ServerSocket ss = new ServerSocket( 5001 ); //通过accept方法获取连接过来的客户端对象。 while ( true ) { Socket s = ss.accept(); String ip = s.getInetAddress().getHostAddress(); System.out.println(ip+ "has been connected" ); //获取客户端发送过来的数据,使用客户端对象的读取流来读取数据。 InputStream in = s.getInputStream(); byte [] buf = new byte [ 1024 ]; int len = in.read(buf); System.out.println( new String(buf, 0 ,len)); s.close(); //关闭客户端. } //ss.close();//需要时关闭服务端 } } |