基于UDP协议的socket编程示例

客户端

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 LoginClient {
public static void main(String[] args) {
String info = "你好,我想咨询一个问题";
byte[] infos = info.getBytes();
//IP地址获取方法
InetAddress ia;
DatagramSocket socket =null;
try {
ia = InetAddress.getByName("localhost");
DatagramPacket dp = new DatagramPacket(infos, infos.length, ia, 5000);
socket = new DatagramSocket();
socket.send(dp); //接收服务端信息
byte[] replys = new byte[1024];
DatagramPacket dp1 = new DatagramPacket(replys,replys.length);
socket.receive(dp1);
String reply = new String(dp1.getData(),0,dp1.getData().length);
System.out.println("服务器说:"+reply); } catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
socket.close();
} }
}

 服务器端

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketException; public class LoginService {
public static void main(String[] args) {
DatagramSocket socket = null;
byte[] info = new byte[1024];
DatagramPacket dp = new DatagramPacket(info, info.length);
try {
socket = new DatagramSocket(5000);
socket.receive(dp); String infos = new String(dp.getData(), 0, dp.getData().length);
System.out.println("客户端说:"+infos); //给客户端一个响应
String reply = "你好,有什么问题请说";
SocketAddress sa = dp.getSocketAddress();
DatagramPacket dp1 = new DatagramPacket(reply.getBytes(), 0, reply.getBytes().length, sa);
socket.send(dp1); } catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
socket.close();
} }
}
上一篇:java socket编程基础(转)


下一篇:学生信息管理系统(c语言)