码迷,mamicode.com
首页 > 编程语言 > 详细

java 网络编程-UDP-双人交互

时间:2019-08-26 21:16:10      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:main   input   cli   end   ams   net   tar   buffered   break   

发送端

public class my implements Runnable {
private DatagramSocket client ;
private BufferedReader reader;
private String toip; //对方的ip
private int toport; //对方的端口
public my(int port,String toip,int toport)
{
    try {
        client=new DatagramSocket(port);
        reader=new BufferedReader(new InputStreamReader(System.in));
        this.toip=toip;
        this.toport=toport;
    } catch (SocketException e) {
        e.printStackTrace();
    }
}
public void run()
{
    while(true)
    {
        String s;
        try {
            s = reader.readLine();

            byte[] datas=s.getBytes();

            DatagramPacket packet=new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toip,this.toport));

            client.send(packet);
            if(s.equals("bye"))
            {
                break;
            }
        } catch (IOException e) {

            e.printStackTrace();
        }

    }
    client.close();
}
}

接收端:使用面向对象封装

public class you implements Runnable{

private DatagramSocket server;
private int port;
private String from;
public you(int port,String from)
{
    this.port=port;
    this.from=from;
    try {
        server=new DatagramSocket(port);
    } catch (SocketException e) {
        e.printStackTrace();
    }
}
public void run()
{
    while(true)
    {
        byte[] container=new byte[1024*60];

        DatagramPacket packet=new DatagramPacket(container,0,container.length);

        try {
            server.receive(packet);

            byte[] datas=packet.getData();
            int len=packet.getLength();

            String data=new String(datas,0,datas.length);
            System.out.println(from+":"+data);

            if(data.equals("bye"))
            {
                break;
            }
        } catch (IOException e) {

            e.printStackTrace();
        }
    }
    server.close();

}
}

加入多线程实现双向交流

public class student {

public static void main(String[]args)
{
    new Thread(new my(9999,"localhost",8888)).start();//发送

    new Thread(new you(7777,"teacher")).start(); //接收
}
}

public class teacher {

public static void main(String[]args)
{
    new Thread(new you(8888,"student")).start();//接收

    new Thread(new my(5555,"localhost",7777) ).start();//发送
}
}

java 网络编程-UDP-双人交互

标签:main   input   cli   end   ams   net   tar   buffered   break   

原文地址:https://blog.51cto.com/14437184/2432739

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!