java udp 服务器_Java UDP 服务器与客户端的问题
該樓層疑似違規已被系統折疊?隱藏此樓查看此樓
package UDP_Client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
public class UDP_Client {
private InetAddress remoteHost = InetAddress.getLocalHost();
private int remoteport = 9999;
private DatagramSocket datagramSocket = null;
public UDP_Client()throws IOException{
datagramSocket = new DatagramSocket(null);
datagramSocket.setReuseAddress(true);
datagramSocket.bind(new InetSocketAddress(remoteHost,remoteport));
}
public void Echo(){
try {
BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
String message = localReader.readLine();
byte[] outputData = message.getBytes();
DatagramPacket outputPacket = new DatagramPacket(outputData, outputData.length,remoteHost,remoteport);
outputPacket.setData(outputData);
datagramSocket.send(outputPacket);//給Server發數據包
//System.out.println(new String(outputPacket.getData(),0,outputPacket.getLength()));
while( true ){
DatagramPacket inputPacket = new DatagramPacket(new byte[512], 512);
datagramSocket.receive(inputPacket);
message = new String(inputPacket.getData(),0,inputPacket.getLength());
System.out.println(message);
if( message.equals("no more data !") || (message == null) )
break;
}
} catch (UnknownHostException e) { e.printStackTrace(); }
catch (IOException e) {e.printStackTrace(); }
finally{datagramSocket.close();}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
new UDP_Client().Echo();
}
}
總結
以上是生活随笔為你收集整理的java udp 服务器_Java UDP 服务器与客户端的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3怎么使用pyrex_Win
- 下一篇: java数组实验报告_Java实验一实验