问答文章1 问答文章501 问答文章1001 问答文章1501 问答文章2001 问答文章2501 问答文章3001 问答文章3501 问答文章4001 问答文章4501 问答文章5001 问答文章5501 问答文章6001 问答文章6501 问答文章7001 问答文章7501 问答文章8001 问答文章8501 问答文章9001 问答文章9501
你好,欢迎来到懂视!登录注册
当前位置: 首页 - 正文

2个Java聊天小程序

发布网友 发布时间:2022-11-09 14:24

我来回答

4个回答

热心网友 时间:2023-11-19 04:18

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
class MyChatter extends JFrame {
private JLabel jLName = new JLabel();
private JTextField jTName = new JTextField();
private JLabel jLSendMss = new JLabel();
private JLabel jLReceiveMss = new JLabel();
private JButton jBSend = new JButton();
private JButton jBClear = new JButton();
private JScrollPane jScrollPane1 = new JScrollPane();
private JTextPane jTSendMss = new JTextPane();
private JScrollPane jScrollPane2 = new JScrollPane();
private JTextPane jTReceiveMss = new JTextPane();

//窗口适配器
private MyWindowAdapter mwa=null;

//通讯用成员变量
private byte[] receiveBuf=new byte[1000];
private byte[] sendBuf=null;
private DatagramSocket datagramServer=null;
private DatagramSocket datagramClient=null;
private DatagramPacket receivePacket=null;
private DatagramPacket sendPacket=null;
private static final int PORT=5000;
private InetAddress inetAddr=null;
private Server server=null;
private String machineName=null;
private String sendMss=null;

class Server extends Thread{

public Server(){
start();
}

public void run(){
while(true){
try{
//System.out.println(datagramServer);
datagramServer.receive(receivePacket);
displayMss();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}

class MyWindowAdapter extends WindowAdapter{
public void windowClosing(WindowEvent e) {
close();
System.exit(0);
}
}

class MyKeyAdapter extends KeyAdapter{
public void keyPressed(KeyEvent e){
//System.out.println(e.getKeyCode());
if(e.isShiftDown()&&e.getKeyCode()==10){
sendReady();
}
}
}

private void sendReady(){
if(!checkMachineName()){
return;
}
if(!checkSendMss()){
return;
}
if(sendMss()){
JOptionPane.showMessageDialog(null,"发送消息成功!","提示",JOptionPane.ERROR_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null,"发送消息失败!","提示",JOptionPane.ERROR_MESSAGE);
}
}

private boolean sendMss(){
try{
sendPacket=toDatagram(sendMss,inetAddr,PORT);
datagramClient.send(sendPacket);
}
catch(Exception e){
return false;
}
return true;
}

private DatagramPacket toDatagram(String s,InetAddress destIA,int destPort){
//sendBuf=new byte[s.length()+1];
//s.getBytes(0,s.length(),sendBuf,0);
try{
sendBuf=s.getBytes("GB2312");
}
catch(Exception e){

}
return new DatagramPacket(sendBuf,sendBuf.length,destIA,destPort);
}

private boolean checkMachineName(){
machineName=jTName.getText();
if(machineName.length()==0){
JOptionPane.showMessageDialog(null,"请输入机器名!","警告",JOptionPane.ERROR_MESSAGE);
return false;
}
try{
inetAddr=InetAddress.getByName(machineName);
}
catch(UnknownHostException e){
JOptionPane.showMessageDialog(null,"不能识别的机器名或者机器不存在!","警告",JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}

private boolean checkSendMss(){
sendMss=jTSendMss.getText();
if(sendMss.length()==0){
JOptionPane.showMessageDialog(null,"要发送的消息不能为空!","警告",JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}

private void displayMss(){
String mss=null;
String tmp=jTReceiveMss.getText();
try{
mss=new String(receivePacket.getData(),0,receivePacket.getLength(),"GB2312");
}
catch(Exception e){

}
jTReceiveMss.setText(tmp+mss+"\n");
}

private void close(){

}

private void init() throws IOException{
mwa=new MyWindowAdapter();
datagramServer=new DatagramSocket(PORT);
datagramClient=new DatagramSocket();
receivePacket=new DatagramPacket(receiveBuf,receiveBuf.length);
jTSendMss.addKeyListener(new MyKeyAdapter());
server=new Server();
}

public MyChatter() throws HeadlessException {
try {
jbInit();
init();
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws HeadlessException {
MyChatter myChatter1 = new MyChatter();
myChatter1.addWindowListener(myChatter1.mwa);
myChatter1.setSize(400,410);
myChatter1.setVisible(true);
}
private void jbInit() throws Exception {
jLName.setText("机器名或IP地址:");
jLName.setBounds(new Rectangle(15, 7, 108, 18));
this.getContentPane().setLayout(null);
jTName.setBounds(new Rectangle(13, 27, 368, 22));
jLSendMss.setText("发送消息:");
jLSendMss.setBounds(new Rectangle(12, 54, 92, 20));
jLReceiveMss.setText("接收消息:");
jLReceiveMss.setBounds(new Rectangle(12, 208, 86, 19));
jBSend.setBounds(new Rectangle(97, 178, 68, 19));
jBSend.setText("发送");
jBSend.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jBSend_actionPerformed(e);
}
});
jBClear.setText("清空");
jBClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jBClear_actionPerformed(e);
}
});
jBClear.setBounds(new Rectangle(224, 179, 68, 19));
this.setResizable(false);
this.setTitle("张辉的聊天程序");
jScrollPane1.setBounds(new Rectangle(13, 77, 368, 90));
jScrollPane2.setBounds(new Rectangle(13, 228, 368, 145));
jTReceiveMss.setEditable(false);
this.getContentPane().add(jLName, null);
this.getContentPane().add(jTName, null);
this.getContentPane().add(jLSendMss, null);
this.getContentPane().add(jLReceiveMss, null);
this.getContentPane().add(jBSend, null);
this.getContentPane().add(jBClear, null);
this.getContentPane().add(jScrollPane1, null);
this.getContentPane().add(jScrollPane2, null);
jScrollPane2.getViewport().add(jTReceiveMss, null);
jScrollPane1.getViewport().add(jTSendMss, null);
}

void jBClear_actionPerformed(ActionEvent e) {
jTSendMss.setText("");
}

void jBSend_actionPerformed(ActionEvent e) {
sendReady();
}
}
绝对能用,OK!给分!!!

热心网友 时间:2023-11-19 04:18

基于udp的没有写过;
不过tcp的倒是有;
先运行Server端

//ChatServer.java
import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
boolean started = false;
ServerSocket ss = null;

List<Client> clients = new ArrayList<Client>();

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);
//dis.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
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) {
clients.remove(this);
System.out.println("对方退出了!我从List里面去掉了!");
//e.printStackTrace();
}
}

public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
System.out.println(str);
for(int i=0; i<clients.size(); i++) {
Client c = clients.get(i);
c.send(str);
//System.out.println(" a string send !");
}
/*
for(Iterator<Client> it = clients.iterator(); it.hasNext(); ) {
Client c = it.next();
c.send(str);
}
*/
/*
Iterator<Client> it = clients.iterator();
while(it.hasNext()) {
Client c = it.next();
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();
}

}
}

}
}

//ChatClient.java
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();
}

/*
try {
bConnected = false;
tRecv.join();
} catch(InterruptedException e) {
e.printStackTrace();
} finally {
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();
//taContent.setText(str);
tfTxt.setText("");

try {
//System.out.println(s);
dos.writeUTF(str);
dos.flush();
//dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}

}

}

private class RecvThread implements Runnable {

public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
//System.out.println(str);
taContent.setText(taContent.getText() + str + '\n');
}
} catch (SocketException e) {
System.out.println("退出了,bye!");
} catch (EOFException e) {
System.out.println("推出了,bye - bye!");
} catch (IOException e) {
e.printStackTrace();
}

}

}
}

热心网友 时间:2023-11-19 04:19

我也想要 也发个给我呗 不胜感激!!!
邮箱 : keaixianer@126.com

热心网友 时间:2023-11-19 04:19

以前好像做过,回去找找看~找到发给你
声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。
E-MAIL:11247931@qq.com
怎么避免脱档 如何避免退档情况发生 考生如何避免被退档 什么人不能交朋友? 歌颂母语的名言4句 关于母语的名言10则,谢谢各位 五年级亲近母语的8个名言警句 急 为什么有的人命里晚婚配偶星在时柱上适合晚婚 常用路亚假饵种类 路亚什么饵钓什么鱼 求比较,ACER ASPIRE 5950G I7-2630(宏基)和ASUS A53SV 4核心 I7-2630... 清肺下火,只要泡这些东西喝,就能即刻清爽怡人 找本小说:都市的,主角带着记忆重生了知道未来会发生的事情和股票走向,利用记忆发展。有个情节是他好兄 《仙剑奇侠传7》怎么样,值得一买吗 货运资格证b2a2通用吗 幻晓伊怎么了 安格鲁宠物貂换毛需要多长时间 安格鲁貂是不是冬眠了 傲慢与偏见白芥子怎么能看 中国足球联赛是我国最晚实行职业化改革的体育赛事吗 酥脆和沙哑的近义词、反义词 热忱的近,反义词;沙哑的近,反义词;辉煌的近反义词 贵由是怎样死的? 桂林电子中等专业学校在那里? 没有参加中招考试可以上中专吗?有什么学校? 桂林电子中等专业学校的专业开设 桂林电子中等专业学校的办学理念 佳通舒适f22价格400元贵吗 2017款美版奔驰GLS450七座SUV现车最低配置多少钱 2017款奔驰GLS450美规版多少钱大型SUV七座报价 2017款奔驰GLS450加拿大版现车最低价格进口七座奔驰GLS450多少钱 精粤是不是山寨主板 精粤主板怎么样 华南金桥的主板好用还是精粤的主板好用 精粤主板是哪家代工 精粤h610i为什么火了 车上的GPS怎么检测? 北舞附中招生要求 满七个月的婴儿,你觉得都应该学会哪些东西? 物流英语如何学习? 我现在学物流专业,想学点英语以后方便就业,请问学要哪方面的英语? 求:物流英语总结 物流英语 “物流学”的英文是? 学物流需要会英语吗? 物流英语怎么能在短时间内学会? C++实现堆栈类(数据用数组存放) 用链表和数组两种方式分别实现栈的出栈、入栈、取栈顶元素、判空、查找等操作。 我的苹果手机型号MD298CH/A序号DNRL4ZXPDTWF是真的? 录音怎么和文字结合在一起 天上人间的反义词
  • 焦点

最新推荐

猜你喜欢

热门推荐