- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.net.SocketException;
- public class Socket{
- public static void main(String[] args) throws SocketException {
-
- DatagramSocket send = new DatagramSocket();
- DatagramSocket rece = new DatagramSocket(11011);
- new Thread(new SendSocket(send)).start();
- new Thread(new ReceSocket(rece)).start();
- }
- }
- class SendSocket implements Runnable {
- DatagramSocket ds;
- SendSocket(DatagramSocket ds){
- this.ds = ds;
- }
- public void run(){
- try {
- BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
- String line = null;
- while((line =bufr.readLine())!= null){
- if("886".equals(line))
- break;
- byte [] buf = line.getBytes();
- DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName("172.17.55.107"),11011);
- ds.send(dp);
- }
- }
- catch (Exception e) {
- throw new RuntimeException("发送端失败");
- }
- finally {
- ds.close();
- }
- }
- }
- class ReceSocket implements Runnable{
- DatagramSocket ds;
- ReceSocket(DatagramSocket ds){
- this.ds = ds;
- }
- public void run(){
- try {
- while(true){
- byte [] buf = new byte [1024];
- DatagramPacket dp = new DatagramPacket(buf, buf.length);
- ds.receive(dp);
- String ip = dp.getAddress().getHostAddress();
- String data = new String(dp.getData(),0,dp.getLength());
- System.out.println(ip+"..."+data);
- }
- } catch (Exception e) {
- throw new RuntimeException("接收端失败");
- }
- }
- }
复制代码
此程序有何问题,使用DOS命令行,怎样才能收到数据??? |
|