【java編程】Socket編程之UDP類比簡單聊天功能__編程

來源:互聯網
上載者:User

簡單介面:

思路:
1.先建立上圖中的介面
2.添加相關的Event監聽事件
3.使用多線程來設計發送端和接收端
4.在發送按鈕裡分別建立發送端和接收端的Thread啟動線程。
5.最後在主程式分別傳入發送和接收的DatagramSocket服務(保證唯一性)

import java.net.*;import java.io.*;import java.awt.*;import java.awt.event.*;class ChatDemo {    public static void main(String[] args) throws SocketException,UnknownHostException    {        DatagramSocket send=new DatagramSocket();        DatagramSocket receive=new DatagramSocket(10001);        new FrameDemo(send,receive);    }}class FrameDemo{       private Button clearBut;    private DatagramSocket send;    private DatagramSocket receive;    private Frame f;    private TextArea sendArea;    private TextArea receiveArea;    private Button but;    FrameDemo(DatagramSocket send,DatagramSocket receive)    {        this.send=send;        this.receive=receive;        init();    }    public void init()    {        f=new Frame("聊天面板");        f.setBounds(600,500,500,500);        f.setLayout(new FlowLayout());        sendArea=new TextArea();        receiveArea=new TextArea();             f.add(receiveArea);        f.add(sendArea);        clearBut=new Button("清屏");        but=new Button("發送");        f.add(clearBut);        f.add(but);        myEvent();        f.setVisible(true);         }    public void myEvent()    {        f.addWindowListener(new WindowAdapter()        {            public void windowClosing(WindowEvent e)            {                System.exit(0);            }        });        but.addActionListener(new ActionListener()        {            public void actionPerformed(ActionEvent e)            {                               new Thread(new  send(send,sendArea)).start();                new Thread(new receive(receive,receiveArea)).start();            }        });        clearBut.addActionListener(new ActionListener()        {            public void actionPerformed(ActionEvent e)            {                receiveArea.setText("");            }        });    }}//接收class receive implements Runnable{    private DatagramSocket ds;    private TextArea receiveArea;    receive(DatagramSocket ds,TextArea receiveArea)    {        this.ds=ds;        this.receiveArea=receiveArea;    }    public void run()    {                //建立資料包        byte[] buf=new byte[1024];        DatagramPacket dp=new DatagramPacket(buf,buf.length);                   try            {                ds.receive(dp);                     }            catch (IOException e)            {                throw new RuntimeException("接收端錯誤");            }            String ip=dp.getAddress().getHostAddress();            String data=new String(dp.getData(),0,dp.getLength());            receiveArea.append(ip+"\r\n"+data+"\r\n");    }}//發送端class send implements Runnable{    private TextArea sendArea;    private DatagramSocket ds;    send(DatagramSocket ds,TextArea sendArea)     {        this.ds=ds;        this.sendArea=sendArea;    }    public void run()     {               String sendData=sendArea.getText();        sendArea.setText("");           //建立資料包        byte[] buf=sendData.getBytes();        DatagramPacket dp=null;        try        {            dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10001);                         }        catch (UnknownHostException e)        {            throw new RuntimeException("發送端錯誤");        }        try        {            if(buf.length==0)                return;            ds.send(dp);                            }        catch (IOException e)        {            throw new RuntimeException("發送端錯誤");        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.