⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 udpchat.java

📁 数据报的收发
💻 JAVA
字号:
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class UDPChat extends JFrame{
	private JLabel label1,label2;
	private JTextField textField;
	private JTextArea textArea;
	private JButton button1,button2;
	public UDPChat (){
    super("聊天工具");
    Container container=getContentPane();
    container.setBackground(Color.LIGHT_GRAY);
    container.setLayout(new FlowLayout());
    label1=new JLabel("请输入要发送的信息:");
    container.add(label1);
    textField=new JTextField(15);
    container.add(textField);
    textArea=new JTextArea(10,33);
    container.add(textArea,null);
    button1=new JButton("发送");
    container.add(button1);
    button2=new JButton("删除");
    container.add(button2);
    ButtonHandler handler2=new ButtonHandler();
    button1.addActionListener(handler2);
    button2.addActionListener(handler2);
    setSize(400,300);
    setVisible(true);
    while(true){
    	try{
			DatagramSocket receiveSocket=new DatagramSocket(5000);
			byte buf[]=new byte[1000];
			DatagramPacket receivePacket=new DatagramPacket(buf,buf.length);
			System.out.println("starting to receive packet");
			while(true){
				receiveSocket.receive(receivePacket);
				String name=receivePacket.getAddress().toString();
				System.out.println("\n主机:"+name+"\n端口:"+receivePacket.getPort());
				String s=new String(receivePacket.getData(),0,receivePacket.getLength());
		    	this.textArea.setText("127.0.0.1:"+s);
			}
		}
		catch(SocketException e){
			e.printStackTrace();
			System.exit(1);
		}
		catch(IOException e){
			System.out.println("网络通讯出现错误,问题在"+e.toString());
	}
	}
   }
   public static void main(String args[]){
   UDPChat application =new UDPChat();
   application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ButtonHandler implements ActionListener{
  public void actionPerformed(ActionEvent event){
    if(event.getSource()==button1)
    {
       send();

       }
    else if(event.getSource()==button2)
       textField.setText("");

    }
   void send(){
   	try{
			DatagramSocket sendSocket=new DatagramSocket(3456);
			String string=textField.getText();
			byte[] databyte=new byte[100];
			databyte=string.getBytes();
			DatagramPacket sendPacket=new DatagramPacket(databyte,string.length(),
			InetAddress.getByName("127.0.0.1"),5000);
			sendSocket.send(sendPacket);
		    textArea.setText("127.0.0.1:"+string+"\n");
			System.out.println("send the data:hello!this is the client");

		}
		catch(SocketException e){
			System.out.println("不能打开数据报Socket,或数据报Socket无法与指定端口连接!");
		}
		catch(IOException ioe){
			System.out.println("网络通信出现错误,问题在"+ioe.toString());
		}
	}
   }
 }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -