日期:2014-05-20  浏览次数:20742 次

基于JAVA的聊天系统
这是毕业设计,求大神给我一些思路
传输与文字聊天工具. 聊天工具分为服务器端和客户端两大模块。

关键问题:
     聊天工具分为服务器端和客户端,以及图形化界面。简单分析服务器端和客户端所要完成的任务。
(1)服务器端应当建立一个ServerSocket,并且不断进行侦听是否有客户端连接或者断开连接(包括判断没有响应的连接超时)。
(2)服务器端应当是一个信息发送中心,所有客户端的信息都传到服务器端,由服务器端根据要求分发信息。
(3)客户端与服务器端建立通信通道,向服务器端发送信息。
(4)客户端接收来自服务器的信息。

------解决方案--------------------
代码给你吧,有不懂的可以问我
package test;

import java.awt.*;
import java.awt.event.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Iterator;

import test.ChatServer.ClientThread;
// 客户端代码
public class ChatClient extends Frame {
Socket s = null;
DataOutputStream dos;
DataInputStream dis;
TextArea ta = null;
TextField tf = null;
String str = null;

public static void main(String[] args) {
ChatClient cc = new ChatClient();
cc.lauchFrame();
cc.connect();

}

public void lauchFrame() {
ta = new TextArea();
tf = new TextField();

this.setTitle("聊天系统");
this.setBounds(400, 200, 400, 300);
this.setVisible(true);
this.add(ta, BorderLayout.NORTH);
this.add(tf, BorderLayout.SOUTH);
pack();

this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
            disconnect();
System.exit(0);
}
});
tf.addActionListener(new TFActionListener());
}

private class TFActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
str = tf.getText();
tf.setText("");
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}

public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
new Thread( new ClientThread2()).start();
}

public void disconnect() {
try {
if (dos != null)
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class ClientThread2 implements Runnable {
public void run() {
try {
while (true) {
str = dis.readUTF();
ta.setText(ta.getText() + str + '\n');
}
} catch (IOException e) {
System.out.println("a client closed");
// e.printStackTrace();
} finally {
try {
if (dis != null)
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}