扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
一个Client端一个server端,先启动server端进行监听响应client端,然后启动client端进行聊天
成都创新互联-专业网站定制、快速模板网站建设、高性价比忻州网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式忻州网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖忻州地区。费用合理售后完善,十余年实体公司更值得信赖。
//时间关系,粗略的做了一下,一个模拟UDP协议的测试,图标,IP,以及端口都可以设成
//发送者端的电脑参数!
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.Serializable;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Day03_A extends JFrame implements Serializable {
private static final long serialVersionUID = 57L;
private JTextArea txtRece, txtSend;// 接受与发送文本域!
private JPanel jp1, jp2;// 面板!
private JScrollPane jsp;
private JLabel jab;// 标签
private JButton jb;// 按钮
private JMenuBar jmb;// 窗体状态栏
private JMenuItem a=null,b=null;
private DatagramSocket dsend = null, drece;
private DatagramPacket dp1, dp2;
private byte[] by1, by2;
private String[][][] menArr= {{{"语言"},{"中文","英文"}}, {{"字体"},{"隶书","彩云",}},{{"辅助"},{"放大","缩小"}}, {{"功能"},{"计算","闹钟"}}};
Day03_A() {
by2 = new byte[1024];
this.setTitle("山寨QQ测试");// 窗体标题
this.setBounds(300, 300, 400, 500);// 位置及大小!
this.setResizable(false);
this.setIconImage(new ImageIcon("E:/Java_Worker/Day_41学习_Gui/src/com/djw/swing01/qq.png").getImage());
this.setLayout(new GridLayout(2, 1));// 网格模式2行1列
init();
this.setJMenuBar(jmb);
this.setVisible(true);
}
private void init() {
jmb = new JMenuBar();
for(int i=0;imenArr.length;i++) {
for(int j=0;jmenArr[i].length;j++) {
for(int x=0;xmenArr[i][j].length;x++) {
if(j==0) {
a=new JMenu(menArr[i][j][x]);
}else {
b=new JMenuItem(menArr[i][j][x]);
a.add(b);
}
}
jmb.add(a);
}
}
jp1 = new JPanel();
jp1.setLayout(new BorderLayout());
txtRece = new JTextArea();
jsp = new JScrollPane(txtRece);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.add(jsp);
jp2 = new JPanel();// 面板
jp2.setBackground(new Color(107, 197, 127));
jp2.setLayout(new BorderLayout());
txtSend = new JTextArea();
jab = new JLabel();
jab.setText("[ALT+S]/[回车+CTRL]或者[点击发送按钮]:发送信息");
jab.setHorizontalAlignment(JLabel.CENTER);// 标签文本居中
jb = new JButton("发送");
jp2.add(jab, BorderLayout.NORTH);// 指定到面板北面
jp2.add(txtSend, BorderLayout.CENTER);// 文本放中间
jp2.add(jb, BorderLayout.SOUTH);
this.add(jp2);
myeve();
}
private void myeve() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);// 窗体可关闭
try {
dsend = new DatagramSocket();// 发送端套接字
drece = new DatagramSocket(10008);
} catch (SocketException e) {
e.printStackTrace();
}
re();// 启动无限循环侦听!
txtSend.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent k) {
if (k.isControlDown() k.getKeyCode() == KeyEvent.VK_ENTER) {
se();
}
if (k.isAltDown() k.getKeyCode() == KeyEvent.VK_S) {
se();
}
}
});
jb.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
se();
txtSend.requestFocus();
}
});
}
private void se() {
try {
by1 = txtSend.getText().getBytes();
dp1 = new DatagramPacket(by1, by1.length, InetAddress.getByName("192.168.2.4"), 10008);
dsend.send(dp1);// 推送数据
txtSend.setText(null);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void re() {
new Thread() {
public void run() {
while (true) {
try {
String time = new SimpleDateFormat("MM-dd/HH:mm").format(new Date());
dp2 = new DatagramPacket(by2, by2.length);
drece.receive(dp2);
String ip = dp2.getAddress().getHostAddress();
txtRece.append("用户IP:" + ip + " 时间:");
txtRece.append(time + ": " + System.getProperty("line.separator"));
txtRece.append(new String(by2, 0, dp2.getLength()) + System.getProperty("line.separator"));
txtRece.setCaretPosition(txtRece.getText().length());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
}
public static void main(String[] args) {
new Day03_A();
}
}
类似QQ的聊天工具?有一种叫luma的QQ程序,是用java编写的,而且代码开放,适用于各种安装了java平台的计算机.
不过好像已经不跟新了,可惜了.
腾讯官方现在也提供了java版本的qq现在
1、swing的界面可以直接用netbeans画出来嘛。
2、可以把输出的聊天内容都放在一个StringBuffer里,每打出一句话,就把这句话追加在StringBuffer,然后把StringBuffer里的内容输出到Textarea中。
3、好友列表可以用JList
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ChatRoom extends JFrame implements MouseListener {
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
new ChatRoom();
}
private JFrame frame;
private JTextArea viewArea;
private JTextField viewField;
private JButton button1;
private JButton button2;
private JLabel jlable;
private JTextField MyName;
public ChatRoom(){
frame = new JFrame("Chat Room");
viewArea = new JTextArea(10, 50);
viewField = new JTextField(50);
jlable= new JLabel();
jlable.setText("在线");
button1 = new JButton("Send");
button2 = new JButton("Quit");
MyName = new JTextField();
MyName.setColumns(9);
MyName.setText("飞翔的企鹅 ");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8,1));
panel.add(jlable);
panel.add(MyName);
panel.add(button1);
panel.add(button2);
JScrollPane sp = new JScrollPane(viewArea);
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.add("Center",sp);
frame.add("East",panel);
frame.add("South",viewField);
frame.setSize(500,250);
frame.setVisible(true);
button1.addMouseListener((MouseListener) this);
button2.addMouseListener((MouseListener) this);
}
public void mouseClicked(MouseEvent evt){
String message = "";
message=MyName.getText()+viewField.getText();
if(evt.getSource()==button1){
viewArea.setText(viewArea.getText()+message+ "\n") ;
}
if(evt.getSource()==button2){
message = "退出";
viewArea.setText(message);
viewField.setText("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public void mousePressed(MouseEvent evt){ }
public void mouseReleased(MouseEvent evt){ }
public void mouseEntered(MouseEvent e){ }
public void mouseExited(MouseEvent e){ }
}
简单得很的那种要不要?就像用来应对考试一样。
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
ListClient clients = new ArrayListClient();
public static void main(String[] args) {
new ChatServer().start();
}
public void start() {
try {
ss = new ServerSocket(8888);
started = true;
} catch (BindException e) {
System.out.println("端口使用中....");
System.out.println("请关掉相关程序并重新运行服务器!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
try {
while(started) {
Socket s = ss.accept();
Client c = new Client(s);
System.out.println("a client connected!");
new Thread(c).start();
clients.add(c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = false;
public Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
System.out.println(str);
for(int i=0; iclients.size(); i++) {
Client c = clients.get(i);
c.send(str);
}
}
} catch (EOFException e) {
System.out.println("Client closed!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(dis != null) dis.close();
if(dos != null) dos.close();
if(s != null) {
s.close();
//s = null;
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
客户端,开两个就能聊了……
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame {
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
Thread tRecv = new Thread(new RecvThread());
public static void main(String[] args) {
new ChatClient().launchFrame();
}
public void launchFrame() {
setLocation(400, 300);
this.setSize(300, 300);
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
setVisible(true);
connect();
tRecv.start();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("connected!");
bConnected = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
tfTxt.setText("");
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private class RecvThread implements Runnable {
public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
taContent.setText(taContent.getText() + str + '\n');
}
} catch (SocketException e) {
System.out.println("bye!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流