UDP案例----聊天程序

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.*;

import javax.swing.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT;

class Test extends JFrame {

	public Test() {
		setUpUI();
		initSocket();
		setListener();
	}

	private static final int DEFAULT_PORT = 8899;

	private JLabel stateLB;
	private JTextArea centerTextArea;
	private JPanel southPanel;
	private JTextArea inputTextArea;
	private JPanel bottomPanel;
	private JTextField ipTextField;
	private JTextField remotePortTF;
	private JButton sendBT;
	private JButton clearBT;
	private DatagramSocket datagramSocket;

	private void setUpUI() {
		setTitle("GUI聊天");
		setSize(400, 400);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setResizable(false);
		setLocationRelativeTo(null);

		stateLB = new JLabel("当前还未启动监听");
		stateLB.setHorizontalAlignment(JLabel.RIGHT);

		centerTextArea = new JTextArea();
		centerTextArea.setEditable(false);
		centerTextArea.setBackground(new Color(211, 211, 211));

		southPanel = new JPanel(new BorderLayout());
		inputTextArea = new JTextArea(5, 20);
		bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
		ipTextField = new JTextField("127.0.0.1", 8);
		remotePortTF = new JTextField(String.valueOf(DEFAULT_PORT), 3);
		sendBT = new JButton("发送");
		clearBT = new JButton("清屏");
		bottomPanel.add(ipTextField);
		bottomPanel.add(remotePortTF);
		bottomPanel.add(sendBT);
		bottomPanel.add(clearBT);
		southPanel.add(new JScrollPane(inputTextArea), BorderLayout.CENTER);
		southPanel.add(bottomPanel, BorderLayout.SOUTH);

		add(stateLB, BorderLayout.NORTH);
		add(new JScrollPane(centerTextArea), BorderLayout.CENTER);
		add(southPanel, BorderLayout.SOUTH);
		setVisible(true);
	}

	private void setListener() {
		sendBT.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				final String ipAddress = ipTextField.getText();
				final String remotePort = remotePortTF.getText();

				if (ipAddress == null || ipAddress.trim().equals("")
						|| remotePort == null || remotePort.trim().equals("")) {
					JOptionPane.showMessageDialog(Test.this, "请输入IP地址和端口号");
					return;
				}
				if (datagramSocket == null || datagramSocket.isClosed()) {
					JOptionPane.showMessageDialog(Test.this, "监听不成功");
					return;
				}

				String sendContent = inputTextArea.getText();
				byte[] buf = sendContent.getBytes();
				try {
					centerTextArea.append("我对 " + ipAddress + ":" + remotePort
							+ "说: \n" + inputTextArea.getText() + "\n\n");
					centerTextArea.setCaretPosition(centerTextArea.getText()
							.length()); // setCaretPosition是设置光标停留位置
					datagramSocket.send(new DatagramPacket(buf, buf.length,
							InetAddress.getByName(ipAddress), Integer
									.parseInt(remotePort)));

					inputTextArea.setText("");
				} catch (IOException el) {
					JOptionPane.showMessageDialog(Test.this, "出错了,发送不成功");
					el.printStackTrace();
				}
			};
		});
		clearBT.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				centerTextArea.setText("");
			}
		});
	}

	private void initSocket(){
		int port = DEFAULT_PORT;
		while(true){
			try{
				if(datagramSocket != null && !datagramSocket.isClosed()){
					datagramSocket.close();
				}
				try{
					port = Integer.parseInt(JOptionPane.showInputDialog(this,"请输入端口号","端口号",JOptionPane.QUESTION_MESSAGE));
					
					if(port<1 || port>65535){
						throw new RuntimeException("端口号超出范围");
					}
				}catch(Exception e){
					JOptionPane.showMessageDialog(null, "您输入的端口不正确,请输入1~65535之间的数");
					continue;
				}
				
				datagramSocket = new DatagramSocket(port);
				startListen();
				
				stateLB.setText("已在 "+port+" 端口监听");
				break;
			}catch(SocketException e){
				JOptionPane.showMessageDialog(this, "端口已被占用,请重新设置端口");
				stateLB.setText("当前还未启动监听");
			}
		}
	}
	
	private void startListen(){
		new Thread(){
			private DatagramPacket p ;
			public void run(){
				byte[] buf = new byte[1024];
				
				p= new DatagramPacket(buf, buf.length);
				while(!datagramSocket.isClosed()){
					try{
						datagramSocket.receive(p);
						centerTextArea.append(p.getAddress().getHostAddress()+":"
								+((InetSocketAddress)p.getSocketAddress())
								.getPort()+" 对我说: \n"
								+new String(p.getData(),0,p.getLength())
								+"\n\n");
						centerTextArea.setCaretPosition(centerTextArea.getText().length());
						
					}catch(IOException e){
						e.printStackTrace();
					}
				}
			}
		}.start();
		
	}

	public static void main(String[] aa) throws IOException {
		new Test();
	}
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值