Java UDP多人聊天系统

客户端

聊天窗口类

package InterFace;


import java.awt.Color;
import java.net.DatagramSocket;


import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;


import Listener.ReceiveMessage;
import Listener.SendButtonListener;


public class ChatInterFace {


//下面定义各种容器及组件
JFrame chatJFrame = new JFrame();
JPanel jP = new JPanel();
JScrollPane messageJScrollPane = new JScrollPane(jP);
JTextArea sendTextArea = new JTextArea();
JButton sendButton = new JButton("send");
SendButtonListener sl = null;
BoxLayout bL = new BoxLayout(jP, BoxLayout.Y_AXIS);

private int port;//下面定义该窗口线程的端口
private int Id;//辨别用户唯一标识
private DatagramSocket ds = null;
private PortCreate pc = null;
ReceiveMessage rM = null;

public ChatInterFace(String name, int Id){


this.Id = Id;
sl = new SendButtonListener(sendTextArea, Id);
pc = new PortCreate(Id);
port = pc.CreatePort();
ds = pc.GetDs();
rM = new ReceiveMessage(jP, ds);

chatJFrame.setTitle("UDPChat" + name);
chatJFrame.setBackground(Color.white);
chatJFrame.setSize(680, 440);
chatJFrame.setVisible(true);
chatJFrame.setLayout(null);
jP.setLayout(bL);
jP.setSize(680, 280);
messageJScrollPane.setSize(680, 280);
messageJScrollPane.setLocation(0, 0);
sendTextArea.setSize(680, 96);
sendTextArea.setLocation(0, 280);
sendButton.setSize(62, 24);
sendButton.setLocation(598, 376);
sendButton.addMouseListener(sl);

chatJFrame.add(messageJScrollPane);
chatJFrame.add(sendTextArea);
chatJFrame.add(sendButton);

rM.start();
}
}

端口注册类

package InterFace;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;


public class PortCreate {

private DatagramSocket ds = null;
private int Id;

public PortCreate(int Id){
this.Id = Id;
}

public int CreatePort(){
int port = -1;
boolean flag = false;

for(int i = 20001; i < 25000; i++){
try {
ds = new DatagramSocket(i);
System.out.println("获取的端口号为 : " + i);
SendPort(Id, i);
return i;
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
continue;
}
}
return port;
}

public DatagramSocket GetDs(){
return ds;
}

private void SendPort(int Id, int port){
String message;
message =  Id + "," + port;
byte[] buf  = message.getBytes();
try {
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getLocalHost(), 21000);
DatagramSocket Ds = new DatagramSocket();
Ds.send(dp);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

发送按钮监听器类

package Listener;


import java.awt.Container;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


import javax.swing.JTextArea;


public class SendButtonListener extends MouseAdapter{
private JTextArea jTA;
private int Id;

public SendButtonListener(JTextArea jTA, int Id){
this.jTA = jTA;
this.Id = Id;
}

public void mouseClicked(MouseEvent e){

new SendMessage(jTA, Id).start();

}
}

信息发送操作类

package Listener;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


import javax.swing.JTextArea;


public class SendMessage extends Thread{

private JTextArea jTA;
private int Id;

public SendMessage(JTextArea jTA, int Id){
this.jTA = jTA;
this.Id = Id;
}

public void run(){
JTextArea messageArea = null;
DatagramPacket dp = null;
DatagramSocket ds = null;
InetAddress ip = null;
try {
ip = InetAddress.getLocalHost();
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
if(ip != null){
ds = new DatagramSocket();
}
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(jTA != null){
messageArea = jTA;
}
if(messageArea != null){
String text = " Id " + Id + " : " + messageArea.getText();
System.out.println("待发送的信息为 " + text);
byte[] buf = text.getBytes();
dp = new DatagramPacket(buf, buf.length, ip, 20099);
try {
ds.send(dp);
messageArea.setText("");
messageArea.updateUI();
messageArea.repaint();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}

信息接受监听类

package Listener;


import java.awt.Panel;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


import javax.swing.JLabel;
import javax.swing.JPanel;


public class ReceiveMessage extends Thread{

private DatagramPacket dp = null;
private DatagramSocket ds = null;
private JPanel jP = null;
private byte[] buf = new byte[1024];

public ReceiveMessage(JPanel jP, DatagramSocket ds){
this.jP = jP;
this.ds = ds;
}

public void run(){
while(true){
if(ds != null){
try {
dp = new DatagramPacket(buf, buf.length);
// ds.setSoTimeout(2000);
ds.receive(dp);
byte[] buf = dp.getData();
String text = new String(buf);
text = text.trim();
System.out.println("收到的消息为 : " + text);
JLabel label = new JLabel(text);
label.setOpaque(true);
label.setSize(400, 24);
jP.add(label);
jP.updateUI();
jP.repaint();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

}

客户端启动类

package Test;


import InterFace.ChatInterFace;


public class TestBench {

public static void main(String []args){


new Thread(){
ChatInterFace cIF1 = new ChatInterFace("用户1", 1);
}.start();
new Thread(){
ChatInterFace cIF2 = new ChatInterFace("用户2", 2);
}.start();
new Thread(){
ChatInterFace cIF3 = new ChatInterFace("用户3", 3);
}.start();
}
}

服务器类

package InterFace;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;


public class Service {

final static int clientSum = 3;
private DatagramSocket dsInfo = null;//接受客户端端口注册
private DatagramSocket dsMessage = null;//接受客户端消息
private DatagramSocket dsSend = null;//向客户端广播消息
private static int[] Id = new int[clientSum];
private static int[] Port = new int[clientSum];

public static void main(String []args){
try {
new Service();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public Service() throws SocketException{
dsInfo = new DatagramSocket(21000);
dsMessage = new DatagramSocket(20099);
dsSend = new DatagramSocket();

//线程1, 监听是否有客户端注册
new Thread(){
public void run(){
int count = 0;
while(count != clientSum){//防止线程1跑得太快, 客户端还没有完整注册
for(int i = 0; i < clientSum; i++){
try {
byte[] dpInfoBuf = new byte[100];
DatagramPacket dpInfo = new DatagramPacket(dpInfoBuf, dpInfoBuf.length);
System.out.println("还没收到端口注册");
dsInfo.receive(dpInfo);
// dsInfo.setSoTimeout(4000);
System.out.println("收到端口注册了!!!");
count++;
String info = new String(dpInfoBuf);
info = info.trim();
String []userInfo = info.split(",");
if(userInfo != null){
Id[i] = Integer.parseInt(userInfo[0]);
Port[i] = Integer.parseInt(userInfo[1]);
System.out.println("注册的端口号为 : " + Port[i]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();

//线程2, 监听是否有客户端信息
new Thread(){
public void run(){
while(true){
byte[] dpMessageBuf = new byte [1024];
DatagramPacket dpMessage = new DatagramPacket(dpMessageBuf, dpMessageBuf.length);
try {
dsMessage.receive(dpMessage);
// dsMessage.setSoTimeout(2000);
System.out.println("服务器收到的消息为 : " + new String(dpMessage.getData()).trim());
for(int i = 0; i < clientSum; i++){
DatagramPacket dpSend = new DatagramPacket(dpMessage.getData(), dpMessage.getData().length, InetAddress.getLocalHost(), Port[i]);
dsSend.send(dpSend);
System.out.println("服务器已经发送数据了");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();

}

}

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值