UDP多人群聊

news/2024/5/18 13:01:23 标签: udp, 网络协议, 网络

一.创建类

二.类

1.Liao类

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.IOException;
import java.lang.String;
 
public class Liao extends JFrame{
	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 datagramSoket;
	private void setUpUI(){
		setTitle("聊天");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(400,400);
		setResizable(false);//窗口大小不可改变
		setLocationRelativeTo(null);//设置窗口相对于指定组件的位置
		stateLB=new JLabel("weijianting");
		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(Liao.this,"请输入IP地址和端口号");
				return;
			}
			if(datagramSoket==null||datagramSoket.isClosed()){
				JOptionPane.showMessageDialog(Liao.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());
				datagramSoket.send(new DatagramPacket(buf,buf.length,InetAddress.getByName(ipAddress),Integer.parseInt(remotePort)));
				inputTextArea.setText("");
			}catch(IOException e1){
				JOptionPane.showMessageDialog(Liao.this, "出错了,发送不成功");
				e1.printStackTrace();
			}
		};
	});
	clearBT.addActionListener(new ActionListener(){
		public void actionPerformed(ActionEvent e){
			centerTextArea.setText("");
		}
	});
}
private void initSocket(){
	int port=DEFAULT_PORT;
	while(true){
		try{
			if(datagramSoket!=null&&!datagramSoket.isConnected()){
				datagramSoket.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;
			}
			datagramSoket=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(!datagramSoket.isConnected()){
				try{
					datagramSoket.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[] args) {
			Liao a=new Liao();
            a.setUpUI();
			a.initSocket();
			a.setListener();
		}
		
}

三.结果

 

 


http://www.niftyadmin.cn/n/5243341.html

相关文章

Unity由“鼠标点不准物体”引发的Camera的相关思考

问题 前段一个同事在使用Unity开发时遇到一个奇怪的问题&#xff0c;使用左键点击发射射线的方式选择物体&#xff0c;总是选不准&#xff0c;尤其是小的物体&#xff0c;鼠标点击到物体上&#xff0c;有时能选上&#xff0c;有时选不上&#xff0c;偶尔点击到物体旁边…

bert其他内容个人记录

Pre-training a seq2seq model BERT只是一个预训练Encoder&#xff0c;有没有办法预训练Seq2Seq模型的Decoder&#xff1f; 在一个transformer的模型中&#xff0c;将输入的序列损坏&#xff0c;然后Decoder输出句子被破坏前的结果&#xff0c;训练这个模型实际上是预训练一个…

C# WPF上位机开发(会员管理软件)

【 声明&#xff1a;版权所有&#xff0c;欢迎转载&#xff0c;请勿用于商业用途。 联系信箱&#xff1a;feixiaoxing 163.com】 好多同学都认为上位机只是纯软件开发&#xff0c;不涉及到硬件设备&#xff0c;比如听听音乐、看看电影、写写小的应用等等。如果是消费电子&#…

java 集合拆分成多个子集合

package com.jiayou.peis.report.biz.utils;import org.apache.poi.ss.formula.functions.T;import java.util.ArrayList; import java.util.List;public class SplitListUtil {/*** 拆分集合* param resultList 原集合* param count 指定的长度* return resultLists 拆分后的…

使用NimoShake将数据从AWS DynamoDB迁移至阿里云MongoDB

本文介绍从AWS DynamoDB到阿里云MongoDB的迁移框架。 它概述了以下步骤&#xff1a; 在阿里云上配置云数据库MongoDB版并应用公网终端节点在 AWS EC2 上安装 Nimoshake将AWS EC2访问阿里云MongoDB版列入白名单配置 Nimoshake 并开始迁移过程验证目标数据库上的增量数据 1. 创…

docker安装及配置mysql

docker 安装mysql 下载镜像文件 下载mysql5.7版本 sudo docker pull mysql:5.7检查是否下载成功 sudo docker images2.创建实例并启动 切换到root下避免每次使用sudo 密码&#xff1a;vagrant docker run -p 3306:3306 --name mysql \ -v /mydata/mysql/log:/var/log/my…

〖大前端 - 基础入门三大核心之JS篇㊼〗- BOM基础之window对象

说明&#xff1a;该文属于 大前端全栈架构白宝书专栏&#xff0c;目前阶段免费&#xff0c;如需要项目实战或者是体系化资源&#xff0c;文末名片加V&#xff01;作者&#xff1a;不渴望力量的哈士奇(哈哥)&#xff0c;十余年工作经验, 从事过全栈研发、产品经理等工作&#xf…

鸿蒙HarmonyOS4.0开发应用学习笔记

黑马程序员鸿蒙4.0视频学习笔记&#xff0c;供自己回顾使用。1.安装开发工具DevEco Studio 鸿蒙harmony开发文档指南 DevEco Studio下载地址 选择或者安装环境 选择和下载SDK 安装总览 编辑器界面 2.TypeScript语法 2.1变量声明 //string 、number、boolean、any、u…