之前学swing做的一个小程序,记录起来。
首先是有两个端,代码一样的差不多。都有发送和接收两个方法,两个端的接收发送的端口刚好相反。由于是在同一台电脑实现,所以主机名也一样。不多说上代码。。。。
聊天室1
package chatroom;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
/**
* 简易聊天室 使用UDP协议进行通讯
* @author Administrator
*
*/
public class Person1_send extends JFrame implements Runnable{
private DatagramSocket socket=null;
SimpleAttributeSet attributeSet =new SimpleAttributeSet();
private JTextField field =new JTextField();
private JTextPane pane1 =new JTextPane();
Document document =pane1.getDocument();
String str ="";
public Person1_send(){}
//构造函数
public Person1_send(DatagramSocket dsocket) throws SocketException{
super("聊天室");
this.socket =dsocket;
// InetAddress address=dsocket.getInetAddress();
StyleConstants.setForeground(attributeSet, Color.RED);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container ct =this.getContentPane();
final JScrollPane pane =new JScrollPane(pane1);
pane1.setEditable(false);
ct.add(pane, BorderLayout.CENTER);
ct.add(field, "South");
field.addActionListener(new ActionListener() {
//聊天面板监听事件
@Override
public void actionPerformed(ActionEvent e) {
try {
//将输入框内容添加到对话框
document.insertString(document.getLength(), "我:"+field.getText()+"\n", attributeSet);
str =field.getText();
field.setText("");
send();
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
}
/**
* 发送信息方法
*/
public void send(){
try {
if(!"".equals(str)&&!socket.isClosed()){
byte[] buf =str.getBytes();
DatagramPacket datagramPacket =new DatagramPacket(buf, buf.length, InetAddress.getByName("localhost"), 1001);
socket.send(datagramPacket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 接收信息方法
*/
@Override
public void run() {
boolean b=false;
try {
if(!b){
b=true;
document.insertString(document.getLength(), "【输入内容按回车键即可发送信息。发送over即可结束聊天。】\n\n", attributeSet);
}
DatagramSocket socket1=new DatagramSocket(1002);//1002接收的端口
byte[] data = new byte[1024];
DatagramPacket packet =new DatagramPacket(data, data.length);
// System.out.println(packet.getAddress().getHostAddress());//发送方ip
// System.out.println(packet.getPort());//发送方端口号
while(true){
socket1.receive(packet);
String str =new String(packet.getData(), 0, packet.getLength());
if("over".equalsIgnoreCase(str)){
document.insertString(document.getLength(), "对方离开了聊天室........ \n", attributeSet);
break;
}
document.insertString(document.getLength(), "对方回复:"+ str+"\t【来自ip:"+packet.getAddress().getHostAddress()+"】\n", attributeSet);
}
} catch (IOException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}finally{
socket.close();
}
}
public static void main(String[] args) throws BadLocationException, IOException {
Person1_send person1 =new Person1_send(new DatagramSocket());
person1.setSize(500, 400);
person1.setVisible(true);
new Thread(person1).start();
}
}
聊天室2
package chatroom;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class Person2_send extends JFrame implements Runnable{
private DatagramSocket socket=null;
SimpleAttributeSet attributeSet =new SimpleAttributeSet();
private JTextField field =new JTextField();
private JTextPane pane1 =new JTextPane();
Document document =pane1.getDocument();
String str ="";
public Person2_send(){}
//构造函数
public Person2_send(DatagramSocket dsocket) throws SocketException{
super("聊天室");
this.socket =dsocket;
// InetAddress address=dsocket.getInetAddress();
StyleConstants.setForeground(attributeSet, Color.RED);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container ct =this.getContentPane();
final JScrollPane pane =new JScrollPane(pane1);
pane1.setEditable(false);
ct.add(pane, BorderLayout.CENTER);
ct.add(field, "South");
field.addActionListener(new ActionListener() {
//聊天面板监听事件
@Override
public void actionPerformed(ActionEvent e) {
try {
//将输入框内容添加到对话框
document.insertString(document.getLength(), "我:"+field.getText()+"\n", attributeSet);
str =field.getText();
field.setText("");
send();
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
}
/**
* 发送信息
*/
public void send(){
try {
if(!"".equals(str)&&!socket.isClosed()){
byte[] buf =str.getBytes();
DatagramPacket datagramPacket =new DatagramPacket(buf, buf.length, InetAddress.getByName("localhost"), 1002);
socket.send(datagramPacket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 接收信息方法
*/
@Override
public void run() {
boolean b=false;
try {
if(!b){
b=true;
document.insertString(document.getLength(), "【输入内容按回车键即可发送信息。发送over即可结束聊天。】\n\n", attributeSet);
}
DatagramSocket socket1=new DatagramSocket(1001);//1001接收的端口
byte[] data = new byte[1024];
DatagramPacket packet =new DatagramPacket(data, data.length);
// System.out.println(packet.getAddress().getHostAddress());//发送方ip
// System.out.println(packet.getPort());//发送方端口号
while(true){
socket1.receive(packet);
String str =new String(packet.getData(), 0, packet.getLength());
if("over".equalsIgnoreCase(str)){
document.insertString(document.getLength(), "对方离开了聊天室........ \n", attributeSet);
break;
}
document.insertString(document.getLength(), "对方回复:"+ str+"\t【来自ip:"+packet.getAddress().getHostAddress()+"】\n", attributeSet);
}
} catch (IOException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}finally{
socket.close();
}
}
public static void main(String[] args) throws BadLocationException, IOException {
Person2_send person1 =new Person2_send(new DatagramSocket());
person1.setSize(500, 400);
person1.setVisible(true);
new Thread(person1).start();
}
}
运行结果: