java udp socket 编程

服务器端:

package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Calendar;

public class UdpTimeServerDemo {

/**
* @param args
*/
public static void main(String[] args) {
byte[] buffer=new byte[1024];
DatagramSocket udpServerSocket;
DatagramPacket udpSendPacket; //发送的包
DatagramPacket udpReceivePacket;//接收的包
try {
udpServerSocket=new DatagramSocket(8000);
udpReceivePacket=new DatagramPacket(buffer,buffer.length);
udpServerSocket.receive(udpReceivePacket);
InetAddress clientAddress = udpReceivePacket.getAddress(); // 得到客户端的地址
int clientPort=udpReceivePacket.getPort(); // 得到客户端的端口
String s = new String(udpReceivePacket.getData());
System.out.println("客户地址:"+clientAddress
+" 客户端口号:"+clientPort);
System.out.println("服务器端收到客户发送数据:"+s);
//发送数据
udpSendPacket = new DatagramPacket(buffer, buffer.length,
clientAddress, clientPort); //设置要发送的数据a
String msg="已收到连接,你好客户端!";
udpSendPacket.setData(msg.getBytes());
udpServerSocket.send(udpSendPacket); //最后,发送数据包
s= new String(udpSendPacket.getData(),0,udpSendPacket.getLength());
System.out.println("服务器响应请求:"+s);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}


客户端:

package udp;

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

public class UdpTimeClientDemo {


public static void main(String[] args) throws IOException {
byte[] buffer=new byte[1024];
DatagramSocket udpClientSocket;
DatagramPacket udpSendPacket;
DatagramPacket udpReceivePacket;
InetAddress hostAddress;

try {
udpClientSocket=new DatagramSocket(3333);
hostAddress = InetAddress.getByName("localhost");
udpSendPacket=new DatagramPacket(buffer,buffer.length,hostAddress,8000);
String s="客户请求连接,你好服务器端!";
udpSendPacket.setData(s.getBytes());
udpClientSocket.send(udpSendPacket);
System.out.println("客户端发送连接请求:"+s);
udpReceivePacket=new DatagramPacket(buffer,buffer.length,hostAddress,8000);
udpClientSocket.receive(udpReceivePacket);
String str=new String(udpReceivePacket.getData());
System.out.println("客户端接收到服务器端响应:"+str);
} catch (SocketException e) {
e.printStackTrace();
}


}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值