2个Java聊天小程序
一个是基于TCP的聊天程序(通过输入ip地址可以像QQ一样聊天)一个是基于UDP的聊天程序将Java源代码发来能用的话我追加100分...
一个是基于TCP的聊天程序(通过输入ip地址 可以像QQ一样聊天)
一个是基于UDP的聊天程序
将Java源代码发来 能用的话 我追加100分 展开
一个是基于UDP的聊天程序
将Java源代码发来 能用的话 我追加100分 展开
4个回答
展开全部
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!给分!!!
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!给分!!!
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
基于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();
}
}
}
}
不过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();
}
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
我也想要 也发个给我呗 不胜感激!!!
邮箱 : keaixianer@126.com
邮箱 : keaixianer@126.com
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
以前好像做过,回去找找看~找到发给你
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询