import java.net.UnknownHostException;
public class TestMain {
public static void main(String[] args) throws UnknownHostException{
GuiChat gc=new GuiChat();
gc.initSocket();
gc.setListender();
}
}
下面这个类主要用来实现客服端与客户端的交互,利用UDP通信,并且监听。可以在一个局域网中实现。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import javax.swing.*;
public class GuiChat extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int DEFAULT_PORT=8899;
private JLabel stateLB; //显示监听状态
private JTextArea centerTextArea; //显示聊天记录
private JPanel southPanel; //最下面的面板
private JTextArea inputTextArea; //聊天输入框
private JPanel bottomPanel;//放置IP输入框, 按钮等
private JTextField ipTextField,remotePortTF;//ip 端口 输入框
private JButton sendBT,clearBT; //发送,清除按钮
private DatagramSocket datagramSocket;
GuiChat() {
//初始化窗口
setTitle("聊天");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setResizable(false);
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);
}
public void setListender() {
sendBT.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final String ipAdress=ipTextField.getText();
final String remotePort=remotePortTF.getText();
if(ipAdress==null||remotePort==null) {
JOptionPane.showMessageDialog(GuiChat.this,"请输入正确的IP和端口号");
return;
}
if(datagramSocket==null||datagramSocket.isClosed()) {
JOptionPane.showMessageDialog(GuiChat.this,"监听失败!");
return;
}
byte[] buf=inputTextArea.getText().getBytes();
try {
centerTextArea.append("我对"+ipAdress+":"+remotePort+"说:\n"+
inputTextArea.getText()+"\n\n");
centerTextArea.setCaretPosition(centerTextArea.getText().length());
datagramSocket.send(new DatagramPacket(buf, buf.length,InetAddress.getByName(ipAdress)
,Integer.parseInt(remotePort)));
inputTextArea.setText("");
} catch (Exception e2) {
JOptionPane.showMessageDialog(GuiChat.this,"未发送成功!");
e2.printStackTrace();
}
}
});
clearBT.addActionListener(new ActionListener() { //为清空按钮添加事件
@Override
public void actionPerformed(ActionEvent e) {
centerTextArea.setText("");
}
});
}
public 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 e3) {
JOptionPane.showMessageDialog(null, "请重新输入!");
continue;
}
datagramSocket=new DatagramSocket(port);
startListener();
stateLB.setText("已经在"+port+"监听");
break;
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "监听失败,请重新设置端口");
stateLB.setText("当前未启动监听!");
}
}
}
public void startListener() { //监听端口 用来接收消息
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 (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
}