首页 > 代码库 > 基于UDP协议的socket编程示例
基于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();
}
}
}
基于UDP协议的socket编程示例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。