📄 udpchat.java
字号:
import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
/**
* The multicast datagram socket class is useful for sending
* and receiving IP multicast packets. A MulticastSocket is
* a (UDP) DatagramSocket, with additional capabilities for
* joining "groups" of other multicast hosts on the internet.
* <P>
* A multicast group is specified by a class D IP address, those
* in the range <CODE>224.0.0.1</CODE> to <CODE>239.255.255.255</CODE>,
* inclusive, and by a standard UDP port number. One would join a
* multicast group by first creating a MulticastSocket with the desired
* port, then invoking the <CODE>joinGroup(InetAddress groupAddr)</CODE>
* method:
* <PRE>
* // join a Multicast group and send the group salutations
* ...
* byte[] msg = {'H', 'e', 'l', 'l', 'o'};
* InetAddress group = InetAddress.getByName("228.5.6.7");
* MulticastSocket s = new MulticastSocket(6789);
* s.joinGroup(group);
* DatagramPacket hi = new DatagramPacket(msg, msg.length,
* group, 6789);
* s.send(hi);
* // get their responses!
* byte[] buf = new byte[1000];
* DatagramPacket recv = new DatagramPacket(buf, buf.length);
* s.receive(recv);
* ...
* // OK, I'm done talking - leave the group...
* s.leaveGroup(group);
* </PRE>
*
* When one sends a message to a multicast group, <B>all</B> subscribing
* recipients to that host and port receive the message (within the
* time-to-live range of the packet, see below). The socket needn't
* be a member of the multicast group to send messages to it.
* <P>
* When a socket subscribes to a multicast group/port, it receives
* datagrams sent by other hosts to the group/port, as do all other
* members of the group and port. A socket relinquishes membership
* in a group by the leaveGroup(InetAddress addr) method. <B>
* Multiple MulticastSocket's</B> may subscribe to a multicast group
* and port concurrently, and they will all receive group datagrams.
* <P>
* Currently applets are not allowed to use multicast sockets.
*/
public class UDPChat extends Frame {
InetAddress group = null;
MulticastSocket socket = null;
String username;
int port;
TextArea textArea = new TextArea();
Panel configPanel = new Panel();
Label ipLabel = new Label();
TextField ipField = new TextField(10);
Label portLabel = new Label();
TextField portField = new TextField(10);
Label nameLabel = new Label();
TextField nameField = new TextField(10);
Panel messagePanel = new Panel();
Button joinButton = new Button();
Button leaveButton = new Button();
TextField messageField = new TextField(80);
Button sendButton = new Button();
Button emptyButton = new Button();
public UDPChat() {
try {
jbInit();
leaveButton.setEnabled(false);
sendButton.setEnabled(false);
textArea.setEditable(false);
pack();
show();
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
UDPChat uDPChat = new UDPChat();
}
private void jbInit() throws Exception {
this.setTitle("多点传送数据报聊天程序 - IP地址范围: 224.0.0.1 ~ 239.255.255.255");
this.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(WindowEvent e) {
this_windowClosing(e);
}
});
ipLabel.setText("IP:");
ipField.setText("225.0.0.1");
portLabel.setText("端口:");
portField.setText("4000");
nameLabel.setText("用户名:");
nameField.setText("匿名");
joinButton.setForeground(Color.blue);
joinButton.setLabel("进入");
joinButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
join();
}
});
leaveButton.setForeground(Color.red);
leaveButton.setLabel("离开");
leaveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
leave();
}
});
messageField.setText("这里输入要发送的文字");
messageField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
send();
}
});
sendButton.setLabel(" 发送 ");
sendButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
send();
}
});
emptyButton.setLabel("清空记录");
emptyButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
emptyButton_actionPerformed(e);
}
});
this.add(configPanel, BorderLayout.NORTH);
configPanel.add(ipLabel);
configPanel.add(ipField);
configPanel.add(portLabel);
configPanel.add(portField);
configPanel.add(nameLabel);
configPanel.add(nameField);
this.add(messagePanel, BorderLayout.SOUTH);
messagePanel.add(messageField);
messagePanel.add(sendButton);
this.add(textArea, BorderLayout.CENTER);
Panel p = new Panel();
p.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = c.weighty = 1;c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0; c.gridy = 0;
p.add(joinButton, c);
c.gridy ++;
p.add(leaveButton, c);
c.gridy ++;
p.add(emptyButton, c);
this.add(p, BorderLayout.WEST);
}
void join() {
username = nameField.getText();
if(username.equals("")) {
textArea.append("请你务必首先输入一个名字.\n");
return;
}
try {
textArea.append("尝试进入聊天室...\n");
group = InetAddress.getByName(ipField.getText());
port = Integer.parseInt(portField.getText());
socket = new MulticastSocket(port);
socket.joinGroup(group);
String message = username + "[" + InetAddress.getLocalHost() + "] 进入聊天室 " + group + "! 端口号"
+ portField.getText() + ".\n";
DatagramPacket hi = new DatagramPacket(message.getBytes(),
message.getBytes().length, group, port);
socket.send(hi);
nameField.setEditable(false);
joinButton.setEnabled(false);
leaveButton.setEnabled(true);
sendButton.setEnabled(true);
new ReaderThread().start();
}catch(Exception ex) {
textArea.append("无法进入聊天室:" + ex + "\n");
ex.printStackTrace();
}
}
void send() {
if(socket == null) return;
try {
String message = username + "[" + InetAddress.getLocalHost() + "] : " + messageField.getText() + "\n";
DatagramPacket hi = new DatagramPacket(message.getBytes(),
message.getBytes().length, group, port);
socket.send(hi);
messageField.requestFocus();
messageField.selectAll();
}catch(Exception ex) {
textArea.append("无法发送消息:" + ex + "\n");
}
}
void leave() {
if(socket == null) return;
try {
textArea.append("尝试离开聊天室...");
String message = username + " 已经离开了聊天室 " + group + "!\n";
DatagramPacket hi = new DatagramPacket(message.getBytes(),
message.getBytes().length, group, port);
socket.send(hi);
socket.leaveGroup(group);
socket.close();
socket = null;
nameField.setEditable(true);
joinButton.setEnabled(true);
leaveButton.setEnabled(false);
sendButton.setEnabled(false);
textArea.append("你已经离开了聊天室!\n");
}catch(Exception ex) {
textArea.append("无法离开聊天室:" + ex + "\n");
ex.printStackTrace();
}
}
void this_windowClosing(WindowEvent e) {
leave();
System.exit(0);
}
class ReaderThread extends Thread {
public void run() {
while(socket != null) {
try {
byte[] buf = new byte[1024];
DatagramPacket recv = new DatagramPacket(buf, buf.length);
socket.receive(recv);
textArea.append(new String(recv.getData()));
}catch(Exception ex) {
}
}
}
}
void emptyButton_actionPerformed(ActionEvent e) {
textArea.setText("");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -