
用java实现QQ群聊
corejava刚全部讲完,要做个QQ群聊要用的有java.io.*java.net.*;还有线程,请高手们帮忙,实现的内容很简单,就是登两个客户端,可以聊天。。不会刷屏...
core java刚全部讲完,要做个QQ群聊
要用的有java.io.*
java.net.*;
还有线程,请高手们帮忙,实现的内容很简单,就是登两个客户端,可以聊天。。
不会刷屏。。。 展开
要用的有java.io.*
java.net.*;
还有线程,请高手们帮忙,实现的内容很简单,就是登两个客户端,可以聊天。。
不会刷屏。。。 展开
4个回答
展开全部
很久前写的代码了,以前能运行。电脑没装jdk,没试试,自己试一下把。。
---------------服务器------------
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
class myframe extends Frame implements ActionListener,WindowListener,Runnable,KeyListener
{
Thread mythread = new Thread(this);
Socket mysocket;
DataInputStream in;
DataOutputStream out;
Label label_ip = new Label("IP");
Label label_port = new Label("Port");
TextField text_ip = new TextField("127.1.1.0",15);
TextField text_port = new TextField("8888",15);
Button button_connect = new Button("连接");
TextArea text_area_show = new TextArea();
TextField text_send = new TextField(45);
Button button_send = new Button("发送");
myframe()
{
Panel panel1 = new Panel();
Panel panel2 = new Panel();
panel1.setLayout(new FlowLayout());
panel1.add(label_ip);
panel1.add(text_ip);
panel1.add(label_port);
panel1.add(text_port);
panel1.add(button_connect);
panel2.setLayout(new FlowLayout());
panel2.add(text_send);
panel2.add(button_send);
add(panel1,BorderLayout.NORTH);
add(text_area_show,BorderLayout.CENTER);
add(panel2,BorderLayout.SOUTH);
text_send.addKeyListener(this);
button_connect.addActionListener(this);
button_send.addActionListener(this);
addWindowListener(this);
this.setTitle("客户端");
setBounds(200,200,400,350);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == button_connect)
{
try
{
String ip = null,port = null;
ip = text_ip.getText();
port = text_port.getText();
mysocket = new Socket(ip, Integer.parseInt(port));
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
}
catch (UnknownHostException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
mythread.start();
}
if(e.getSource() == button_send)
{
if(mysocket.isConnected() == true)
{
String temp = null;
temp = text_send.getText();
try
{
out.writeUTF(temp);
text_send.setText(null);
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void run()
{
while(true)
{
String temp = null;
try
{
temp = in.readUTF();
}
catch (IOException ex)
{
text_area_show.append("服务器退出\n");
return;
}
temp += "\n";
text_area_show.append(temp);
}
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
String temp = null;
temp = text_send.getText();
try
{
out.writeUTF(temp);
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
public class mywindow
{
public static void main(String argv[])
{
myframe f = new myframe();
}
}
-----------客户端-----------
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
class SocketList
{
int length = 0;
Socket socketlist[] = new Socket[10];
SocketList()
{
}
void add(Socket s)
{
if(length == 10)
{
return;
}
socketlist[length] = s;
length++;
}
void Delete(Socket s)
{
int i = 0;
for(i = 0;i < length;i++)
{
if(socketlist[i] == s)
{
break;
}
}
for(int j = i;j < length;j++)
{
socketlist[j] = socketlist[j + 1];
}
length--;
/*
for(int k = 0;k < length;k++)
{
if(socketlist[k].isBound() == true)
{
System.out.print("error");
}
}*/
}
}
class FrameThread extends Thread
{
myframe frame;
FrameThread(myframe f)
{
frame = f;
start();
}
public void run()
{
while(true)
{
InetAddress addr = null;
Socket s = null;
try
{
s = frame.server.accept();
addr = s.getInetAddress();
frame.socketlist.add(s);
for(int i = 0;i < frame.socketlist.length;i++)
{
if(frame.socketlist.socketlist[i] != s )
{
DataInputStream in = new DataInputStream(frame.socketlist.socketlist[i].getInputStream());
DataOutputStream out= new DataOutputStream(frame.socketlist.socketlist[i].getOutputStream());
out.writeUTF(addr + "连接到服务器");
}
}
}
catch (IOException ex)
{
Logger.getLogger(FrameThread.class.getName()).log(Level.SEVERE, null, ex);
}
frame.text_area_show.append(addr + "连接到服务器\n");
try
{
frame.list.add(InetAddress.getLocalHost().getHostAddress() + "-" + s.getPort());
}
catch (UnknownHostException ex)
{
Logger.getLogger(FrameThread.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
new ClientThread(s, frame);
}
catch (IOException ex)
{
Logger.getLogger(FrameThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
class ClientThread extends Thread
{
DataInputStream in = null;
DataOutputStream out = null;
Socket mysocket = new Socket();
myframe frame = null;
InetAddress addr = null;
ClientThread(Socket s,myframe f) throws IOException
{
mysocket = s;
addr = mysocket.getLocalAddress();
frame = f;
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
out.writeUTF("成功连接服务器");
start();
}
public void run()
{
while(true)
{
String temp = null;
try
{
temp = in.readUTF();
for(int i = 0;i < frame.socketlist.length;i++)
{
DataInputStream in_temp = new DataInputStream(frame.socketlist.socketlist[i].getInputStream());
DataOutputStream out_temp = new DataOutputStream(frame.socketlist.socketlist[i].getOutputStream());
out_temp.writeUTF(addr + "说: " + temp);
}
frame.text_area_show.append(addr + "说: " + temp + "\n");
}
catch (IOException ex)
{
frame.socketlist.Delete(mysocket);
frame.text_area_show.append(addr + "退出服务器\n");
for(int i = 0;i < frame.socketlist.length;i++)
{
try
{
DataInputStream in_temp = new DataInputStream(frame.socketlist.socketlist[i].getInputStream());
}
catch (IOException ex1)
{
Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex1);
}
DataOutputStream out_temp = null;
try
{
out_temp = new DataOutputStream(frame.socketlist.socketlist[i].getOutputStream());
}
catch (IOException ex1)
{
Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex1);
}
try
{
out_temp.writeUTF(addr + "退出服务器");
}
catch (IOException ex1)
{
Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex1);
}
}
return;
}
}
}
}
class myframe extends JFrame implements ActionListener,WindowListener,KeyListener
{
List list = new List(16);
TextArea text_area_show = new TextArea(15,40);
TextField text_send = new TextField(50);
Button button_send = new Button("发送");
ServerSocket server = null;
FrameThread thread;
SocketList socketlist = new SocketList();
myframe() throws IOException
{
Panel panel1 = new Panel();
panel1.setLayout(new FlowLayout());
panel1.add(text_area_show);
panel1.add(list);
list.addActionListener(this);
Panel panel2 = new Panel();
panel2.setLayout(new FlowLayout());
panel2.add(text_send);
panel2.add(button_send);
setLayout(new FlowLayout());
add(panel1);
add(panel2);
text_send.addKeyListener(this);
button_send.addActionListener(this);
addWindowListener(this);
server = new ServerSocket(8888);
thread = new FrameThread(this);
setTitle("服务器");
setBounds(200,200,450,330);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == list)
{
text_area_show.append(list.getSelectedItem() + "\n");
}
if(e.getSource() == button_send)
{
for(int i = 0;i < socketlist.length;i++)
{
try
{
DataInputStream in = new DataInputStream(socketlist.socketlist[i].getInputStream());
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
DataOutputStream out = null;
try
{
out = new DataOutputStream(socketlist.socketlist[i].getOutputStream());
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
out.writeUTF(text_send.getText());
text_send.setText(null);
// text_area_show.append(text_send.getText() + "\n");
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
for(int i = 0;i < socketlist.length;i++)
{
try
{
DataInputStream in = new DataInputStream(socketlist.socketlist[i].getInputStream());
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
DataOutputStream out = null;
try
{
out = new DataOutputStream(socketlist.socketlist[i].getOutputStream());
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
out.writeUTF(text_send.getText());
text_area_show.append(text_send.getText() + "\n");
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void keyReleased(KeyEvent e) {}
}
public class mywindow
{
public static void main(String argv[]) throws IOException
{
myframe f = new myframe();
}
}
---------------服务器------------
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
class myframe extends Frame implements ActionListener,WindowListener,Runnable,KeyListener
{
Thread mythread = new Thread(this);
Socket mysocket;
DataInputStream in;
DataOutputStream out;
Label label_ip = new Label("IP");
Label label_port = new Label("Port");
TextField text_ip = new TextField("127.1.1.0",15);
TextField text_port = new TextField("8888",15);
Button button_connect = new Button("连接");
TextArea text_area_show = new TextArea();
TextField text_send = new TextField(45);
Button button_send = new Button("发送");
myframe()
{
Panel panel1 = new Panel();
Panel panel2 = new Panel();
panel1.setLayout(new FlowLayout());
panel1.add(label_ip);
panel1.add(text_ip);
panel1.add(label_port);
panel1.add(text_port);
panel1.add(button_connect);
panel2.setLayout(new FlowLayout());
panel2.add(text_send);
panel2.add(button_send);
add(panel1,BorderLayout.NORTH);
add(text_area_show,BorderLayout.CENTER);
add(panel2,BorderLayout.SOUTH);
text_send.addKeyListener(this);
button_connect.addActionListener(this);
button_send.addActionListener(this);
addWindowListener(this);
this.setTitle("客户端");
setBounds(200,200,400,350);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == button_connect)
{
try
{
String ip = null,port = null;
ip = text_ip.getText();
port = text_port.getText();
mysocket = new Socket(ip, Integer.parseInt(port));
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
}
catch (UnknownHostException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
mythread.start();
}
if(e.getSource() == button_send)
{
if(mysocket.isConnected() == true)
{
String temp = null;
temp = text_send.getText();
try
{
out.writeUTF(temp);
text_send.setText(null);
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void run()
{
while(true)
{
String temp = null;
try
{
temp = in.readUTF();
}
catch (IOException ex)
{
text_area_show.append("服务器退出\n");
return;
}
temp += "\n";
text_area_show.append(temp);
}
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
String temp = null;
temp = text_send.getText();
try
{
out.writeUTF(temp);
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
public class mywindow
{
public static void main(String argv[])
{
myframe f = new myframe();
}
}
-----------客户端-----------
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
class SocketList
{
int length = 0;
Socket socketlist[] = new Socket[10];
SocketList()
{
}
void add(Socket s)
{
if(length == 10)
{
return;
}
socketlist[length] = s;
length++;
}
void Delete(Socket s)
{
int i = 0;
for(i = 0;i < length;i++)
{
if(socketlist[i] == s)
{
break;
}
}
for(int j = i;j < length;j++)
{
socketlist[j] = socketlist[j + 1];
}
length--;
/*
for(int k = 0;k < length;k++)
{
if(socketlist[k].isBound() == true)
{
System.out.print("error");
}
}*/
}
}
class FrameThread extends Thread
{
myframe frame;
FrameThread(myframe f)
{
frame = f;
start();
}
public void run()
{
while(true)
{
InetAddress addr = null;
Socket s = null;
try
{
s = frame.server.accept();
addr = s.getInetAddress();
frame.socketlist.add(s);
for(int i = 0;i < frame.socketlist.length;i++)
{
if(frame.socketlist.socketlist[i] != s )
{
DataInputStream in = new DataInputStream(frame.socketlist.socketlist[i].getInputStream());
DataOutputStream out= new DataOutputStream(frame.socketlist.socketlist[i].getOutputStream());
out.writeUTF(addr + "连接到服务器");
}
}
}
catch (IOException ex)
{
Logger.getLogger(FrameThread.class.getName()).log(Level.SEVERE, null, ex);
}
frame.text_area_show.append(addr + "连接到服务器\n");
try
{
frame.list.add(InetAddress.getLocalHost().getHostAddress() + "-" + s.getPort());
}
catch (UnknownHostException ex)
{
Logger.getLogger(FrameThread.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
new ClientThread(s, frame);
}
catch (IOException ex)
{
Logger.getLogger(FrameThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
class ClientThread extends Thread
{
DataInputStream in = null;
DataOutputStream out = null;
Socket mysocket = new Socket();
myframe frame = null;
InetAddress addr = null;
ClientThread(Socket s,myframe f) throws IOException
{
mysocket = s;
addr = mysocket.getLocalAddress();
frame = f;
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
out.writeUTF("成功连接服务器");
start();
}
public void run()
{
while(true)
{
String temp = null;
try
{
temp = in.readUTF();
for(int i = 0;i < frame.socketlist.length;i++)
{
DataInputStream in_temp = new DataInputStream(frame.socketlist.socketlist[i].getInputStream());
DataOutputStream out_temp = new DataOutputStream(frame.socketlist.socketlist[i].getOutputStream());
out_temp.writeUTF(addr + "说: " + temp);
}
frame.text_area_show.append(addr + "说: " + temp + "\n");
}
catch (IOException ex)
{
frame.socketlist.Delete(mysocket);
frame.text_area_show.append(addr + "退出服务器\n");
for(int i = 0;i < frame.socketlist.length;i++)
{
try
{
DataInputStream in_temp = new DataInputStream(frame.socketlist.socketlist[i].getInputStream());
}
catch (IOException ex1)
{
Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex1);
}
DataOutputStream out_temp = null;
try
{
out_temp = new DataOutputStream(frame.socketlist.socketlist[i].getOutputStream());
}
catch (IOException ex1)
{
Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex1);
}
try
{
out_temp.writeUTF(addr + "退出服务器");
}
catch (IOException ex1)
{
Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex1);
}
}
return;
}
}
}
}
class myframe extends JFrame implements ActionListener,WindowListener,KeyListener
{
List list = new List(16);
TextArea text_area_show = new TextArea(15,40);
TextField text_send = new TextField(50);
Button button_send = new Button("发送");
ServerSocket server = null;
FrameThread thread;
SocketList socketlist = new SocketList();
myframe() throws IOException
{
Panel panel1 = new Panel();
panel1.setLayout(new FlowLayout());
panel1.add(text_area_show);
panel1.add(list);
list.addActionListener(this);
Panel panel2 = new Panel();
panel2.setLayout(new FlowLayout());
panel2.add(text_send);
panel2.add(button_send);
setLayout(new FlowLayout());
add(panel1);
add(panel2);
text_send.addKeyListener(this);
button_send.addActionListener(this);
addWindowListener(this);
server = new ServerSocket(8888);
thread = new FrameThread(this);
setTitle("服务器");
setBounds(200,200,450,330);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == list)
{
text_area_show.append(list.getSelectedItem() + "\n");
}
if(e.getSource() == button_send)
{
for(int i = 0;i < socketlist.length;i++)
{
try
{
DataInputStream in = new DataInputStream(socketlist.socketlist[i].getInputStream());
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
DataOutputStream out = null;
try
{
out = new DataOutputStream(socketlist.socketlist[i].getOutputStream());
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
out.writeUTF(text_send.getText());
text_send.setText(null);
// text_area_show.append(text_send.getText() + "\n");
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
for(int i = 0;i < socketlist.length;i++)
{
try
{
DataInputStream in = new DataInputStream(socketlist.socketlist[i].getInputStream());
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
DataOutputStream out = null;
try
{
out = new DataOutputStream(socketlist.socketlist[i].getOutputStream());
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
out.writeUTF(text_send.getText());
text_area_show.append(text_send.getText() + "\n");
}
catch (IOException ex)
{
Logger.getLogger(myframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void keyReleased(KeyEvent e) {}
}
public class mywindow
{
public static void main(String argv[]) throws IOException
{
myframe f = new myframe();
}
}

2025-05-12 广告
“调研工厂”系北京清研灵智科技有限公司研发的专业智能的线上线下一体化问卷调查和明察暗访平台,支持网络调查、面对面访问、明察暗访、云电话调查、深度访谈、座谈会等功能,同时提供行业定制解决方案。“调研工厂”依托10年专业调研经验,获得了1000...
点击进入详情页
本回答由调研工厂提供
展开全部
服务端:
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
List clients = new ArrayList();
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 clent connected");//调试用语句,可以左移以便将来删除
new Thread(c).start();//启动子线程,主线程负责不断监听客户端的连接
clients.add(c);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
ss.close();
}catch(IOException e2){
e2.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket s = null ;
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; i<clients.size(); i++){
Client c = (Client)clients.get(i);
c.send(str);
}
/* 法2:需要锁定Client,但实际上不需要锁定,只需使用send方法,且效率低
for(Iterator it = clients.iterator(); it.hasNext();){
Client c = (Client)it.next();
c.send(str);
}
*/
}
}catch(EOFException e){
System.out.println("客户端关闭");
} catch(IOException e){
e.printStackTrace();
}finally{
try{
if(dis != null ) dis.close();
if(dos != null ) dos.close();
if(s != null ) s.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
}
}
}
客户端:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
public class ChatClient extends JFrame {
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
JTextField tfTxt = new JTextField();
JTextArea taContent = new JTextArea(20,50);
Thread tRecv = new Thread(new RecvThread());
public static void main(String[] args) {
new ChatClient();
}
public ChatClient(){
this.setLocation(400,300);
this.setSize(300,300);
Container con = this.getContentPane();
con.add(tfTxt,BorderLayout.SOUTH);
con.add(taContent,BorderLayout.NORTH);
pack();
//窗口关闭事件处理
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
this.setVisible(true);
connect();//连接server
tRecv.start(); //启动线程
}
public void connect(){
try {
s = new Socket("127.0.0.1",8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
bConnected = true;
System.out.println("connected");//测试用
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect(){
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 {
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()+"\n"+str);
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
你看看啊 呵呵呵
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
List clients = new ArrayList();
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 clent connected");//调试用语句,可以左移以便将来删除
new Thread(c).start();//启动子线程,主线程负责不断监听客户端的连接
clients.add(c);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
ss.close();
}catch(IOException e2){
e2.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket s = null ;
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; i<clients.size(); i++){
Client c = (Client)clients.get(i);
c.send(str);
}
/* 法2:需要锁定Client,但实际上不需要锁定,只需使用send方法,且效率低
for(Iterator it = clients.iterator(); it.hasNext();){
Client c = (Client)it.next();
c.send(str);
}
*/
}
}catch(EOFException e){
System.out.println("客户端关闭");
} catch(IOException e){
e.printStackTrace();
}finally{
try{
if(dis != null ) dis.close();
if(dos != null ) dos.close();
if(s != null ) s.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
}
}
}
客户端:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
public class ChatClient extends JFrame {
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
JTextField tfTxt = new JTextField();
JTextArea taContent = new JTextArea(20,50);
Thread tRecv = new Thread(new RecvThread());
public static void main(String[] args) {
new ChatClient();
}
public ChatClient(){
this.setLocation(400,300);
this.setSize(300,300);
Container con = this.getContentPane();
con.add(tfTxt,BorderLayout.SOUTH);
con.add(taContent,BorderLayout.NORTH);
pack();
//窗口关闭事件处理
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
this.setVisible(true);
connect();//连接server
tRecv.start(); //启动线程
}
public void connect(){
try {
s = new Socket("127.0.0.1",8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
bConnected = true;
System.out.println("connected");//测试用
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect(){
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 {
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()+"\n"+str);
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
你看看啊 呵呵呵
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
233013958适合1年以内经验者
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
那就去找刷屏的函数~~~~~
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询