服务端和客户端UDP通信demo

本文介绍了一个简单的UDP通信案例,包括服务端和客户端的实现。服务端能够接收客户端发送的消息,并作出回应;客户端则向服务端发送消息并接收回应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

===============服务端

package com.sls.test.socket;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;


public class MyAndroidServerUDPSocket {
private byte[] buffer = new byte[1024];


//接受或发送数据报的套接字
private DatagramSocket ds = null;


//存放数据的数据报
private DatagramPacket packet = null;


private InetSocketAddress socketAddress = null;


private String orgIp;


/**
* 构造函数,绑定主机和端口.

* @param host
*            主机
* @param port
*            端口
* @throws Exception
*/
public MyAndroidServerUDPSocket(String host, int port) throws Exception {
socketAddress = new InetSocketAddress(host, port);
ds = new DatagramSocket(socketAddress);
System.out.println("服务端启动!");
}


public final String getOrgIp() {
return orgIp;
}


/**
* 设置超时时间,该方法必须在bind方法之后使用.

* @param timeout
*            超时时间
* @throws Exception
*/
public final void setSoTimeout(int timeout) throws Exception {
ds.setSoTimeout(timeout);
}


/**
* 获得超时时间.

* @return 返回超时时间.
* @throws Exception
* @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> Creation
*         date: 2007-8-16 - 下午10:34:36
*/
public final int getSoTimeout() throws Exception {
return ds.getSoTimeout();
}


/**
* 绑定监听地址和端口.

* @param host
*            主机IP
* @param port
*            端口
* @throws SocketException
* @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> Creation
*         date: 2007-8-16 - 下午10:36:17
*/
public final void bind(String host, int port) throws SocketException {
socketAddress = new InetSocketAddress(host, port);
ds = new DatagramSocket(socketAddress);
}


/**
* 接收数据包,该方法会造成线程阻塞.

* @return 返回接收的数据串信息
* @throws IOException
* @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> Creation
*         date: 2007-8-16 - 下午10:38:24
*/
public final String receive() throws IOException {
packet = new DatagramPacket(buffer, buffer.length);
ds.receive(packet);
orgIp = packet.getAddress().getHostAddress();
String info = new String(packet.getData(), 0, packet.getLength());
System.out.println("接收信息:" + info);
return info;
}


/**
* 将响应包发送给请求端.

* @param bytes
*            回应报文
* @throws IOException
* @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> Creation
*         date: 2007-8-16 - 下午11:05:31
*/
public final void response(String info) throws IOException {
System.out.println("客户端地址 : " + packet.getAddress().getHostAddress()
+ ",端口:" + packet.getPort());
DatagramPacket dp = new DatagramPacket(buffer, buffer.length,
packet.getAddress(), packet.getPort());
dp.setData(info.getBytes());
ds.send(dp);
}


/**
* 设置报文的缓冲长度.

* @param bufsize
*            缓冲长度
* @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> Creation
*         date: 2007-8-16 - 下午10:47:49
*/
public final void setLength(int bufsize) {
packet.setLength(bufsize);
}


/**
* 获得发送回应的IP地址.

* @return 返回回应的IP地址
* @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> Creation
*         date: 2007-8-16 - 下午10:48:27
*/
public final InetAddress getResponseAddress() {
return packet.getAddress();
}


/**
* 获得回应的主机的端口.

* @return 返回回应的主机的端口.
* @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> Creation
*         date: 2007-8-16 - 下午10:48:56
*/
public final int getResponsePort() {
return packet.getPort();
}


/**
* 关闭udp监听口.

* @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> Creation
*         date: 2007-8-16 - 下午10:49:23
*/
public final void close() {
try {
ds.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}


/**
* 测试方法.

* @param args
* @throws Exception
* @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> Creation
*         date: 2007-8-16 - 下午10:49:50
*/
public static void main(String[] args) throws Exception {
String serverHost = "127.0.0.1";
int serverPort = 3344;
MyAndroidServerUDPSocket udp = new MyAndroidServerUDPSocket(
serverHost, serverPort);
while (true) {
udp.receive();
udp.response("你好,sterning!");


}
}

}


===============================客户端

package com.sls.test.socket;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class MyAndroidClientUDPSocket {

private byte[] buffer = new byte[1024];  
 
    private DatagramSocket ds = null;  

    /** 
     * 构造函数,创建UDP客户端 
     * @throws Exception 
     */  
    public MyAndroidClientUDPSocket() throws Exception {  
        ds = new DatagramSocket();  
    }  

    /** 设置超时时间,该方法必须在bind方法之后使用. 
    * @param timeout 超时时间 
    * @throws Exception 
    * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
    * Creation date: 2007-8-16 - 下午10:55:12 
    */  
   public final void setSoTimeout(final int timeout) throws Exception {  
       ds.setSoTimeout(timeout);  
   }  
 
   /** 
    * 获得超时时间. 
    * @return 返回超时时间 
    * @throws Exception 
    * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
    * Creation date: 2007-8-16 - 下午10:55:25 
    */  
   public final int getSoTimeout() throws Exception {  
       return ds.getSoTimeout();  
   }  
 
   public final DatagramSocket getSocket() {  
       return ds;  
   }  

   /** 
    * 向指定的服务端发送数据信息. 
    * @param host 服务器主机地址 
    * @param port 服务端端口 
    * @param bytes 发送的数据信息 
    * @return 返回构造后俄数据报 
    * @throws IOException 
    * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
    * Creation date: 2007-8-16 - 下午11:02:41 
    */  
   public final DatagramPacket send(final String host, final int port,  
           final byte[] bytes) throws IOException {  
       DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress  
               .getByName(host), port);  
       ds.send(dp);  
       return dp;  
   }  

   /** 
    * 接收从指定的服务端发回的数据. 
    * @param lhost 服务端主机 
    * @param lport 服务端端口 
    * @return 返回从指定的服务端发回的数据. 
    * @throws Exception 
    * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
    * Creation date: 2007-8-16 - 下午10:52:36 
    */  
   public final String receive(final String lhost, final int lport)  
           throws Exception {  
       DatagramPacket dp = new DatagramPacket(buffer, buffer.length);  
       ds.receive(dp);  
       String info = new String(dp.getData(), 0, dp.getLength());  
       return info;  
   }  
 
   /** 
    * 关闭udp连接. 
    * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
    * Creation date: 2007-8-16 - 下午10:53:52 
    */  
   public final void close() {  
       try {  
           ds.close();  
       } catch (Exception ex) {  
           ex.printStackTrace();  
       }  
   }  
 

   /** 
    * 测试客户端发包和接收回应信息的方法. 
    * @param args 
    * @throws Exception 
    * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
    * Creation date: 2007-8-16 - 下午11:03:54 
    */  
   public static void main(String[] args) throws Exception {  
  MyAndroidClientUDPSocket client = new MyAndroidClientUDPSocket();  
       String serverHost = "127.0.0.1";  
       int serverPort = 3344;  
       client.send(serverHost, serverPort, ("你好,阿蜜果!").getBytes());  
       String info = client.receive(serverHost, serverPort);  
       System.out.println("服务端回应数据:" + info);  
   }  


}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值