概述
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class UdpEchoClient {
private DatagramSocket socket = null;
private String serverIp;
private int serverPort;
public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
this.serverIp = serverIp;
this.serverPort = serverPort;
socket = new DatagramSocket();
}
public void start() throws IOException {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("->");
String request = scanner.nextLine();
if(request.equals("exit")){
break;
}
//发送请求
DatagramPacket requestpacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
InetAddress.getByName(serverIp),serverPort);
socket.send(requestpacket);
//收到回应
DatagramPacket responsepacket = new DatagramPacket(new byte[4096],4096);
socket.receive(responsepacket);
String response = new String(requestpacket.getData(),0,responsepacket.getLength()).trim();
System.out.println(response);
}
}
public static void main(String[] args) throws IOException {
UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
client.start();
}
}
最后
以上就是灵巧水杯为你收集整理的UdpEchoClient客户端实现 java的全部内容,希望文章能够帮你解决UdpEchoClient客户端实现 java所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复