服务器之家

服务器之家 > 正文

Java Socket编程实例(二)- UDP基本使用

时间:2020-05-16 16:14     来源/作者:kingxss

一.服务端代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.io.*;
import java.net.*;
 
public class UDPEchoServer {
 
  private static final int ECHOMAX = 255; // Maximum size of echo datagram
 
  public static void main(String[] args) throws IOException {
 
    int servPort = 5500; // Server port
 
    DatagramSocket socket = new DatagramSocket(servPort);
    DatagramPacket packet = new DatagramPacket(new byte[ECHOMAX], ECHOMAX);
 
    while (true) { // Run forever, receiving and echoing datagrams
      socket.receive(packet); // Receive packet from client
      System.out.println("Handling client at " + packet.getAddress().getHostAddress() + " on port " + packet.getPort());
      socket.send(packet); // Send the same packet back to client
      packet.setLength(ECHOMAX); // Reset length to avoid shrinking buffer
    }
    /* NOT REACHED */
  }
}

二.客户端代码:

?
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
38
39
40
41
42
43
44
45
46
47
48
import java.net.*;
import java.io.*;
 
public class UDPEchoClientTimeout {
 
  private static final int TIMEOUT = 3000; // Resend timeout (milliseconds)
  private static final int MAXTRIES = 5; // Maximum retransmissions
 
  public static void main(String[] args) throws IOException {
    InetAddress serverAddress = InetAddress.getByName("127.0.0.1"); // Server address
    int servPort = 5500; // Server port
    // Convert the argument String to bytes using the default encoding
    byte[] bytesToSend = "Hi, World".getBytes();
 
    DatagramSocket socket = new DatagramSocket();
    socket.setSoTimeout(TIMEOUT); // Maximum receive blocking time(milliseconds)
    // Sending packet
    DatagramPacket sendPacket = new DatagramPacket(bytesToSend, bytesToSend.length, serverAddress, servPort);
 
    DatagramPacket receivePacket = // Receiving packet
    new DatagramPacket(new byte[bytesToSend.length], bytesToSend.length);
 
    int tries = 0; // Packets may be lost, so we have to keep trying
    boolean receivedResponse = false;
    do {
      socket.send(sendPacket); // Send the echo string
      try {
        socket.receive(receivePacket); // Attempt echo reply reception
 
        if (!receivePacket.getAddress().equals(serverAddress)) {// Check
                                    // source
          throw new IOException("Received packet from an unknown source");
        }
        receivedResponse = true;
      } catch (InterruptedIOException e) { // We did not get anything
        tries += 1;
        System.out.println("Timed out, " + (MAXTRIES - tries) + " more tries...");
      }
    } while ((!receivedResponse) && (tries < MAXTRIES));
 
    if (receivedResponse) {
      System.out.println("Received: " + new String(receivePacket.getData()));
    } else {
      System.out.println("No response -- giving up.");
    }
    socket.close();
  }
}

上述代码的UDP服务端是单线程,一次只能服务一个客户端。

以上就是本文的全部内容,查看更多Java的语法,也希望大家多多支持服务器之家。

标签:

相关文章

热门资讯

歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分 2019-06-21
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
超A是什么意思 你好a表达的是什么
超A是什么意思 你好a表达的是什么 2019-06-06
返回顶部