使用Socket制作聊天室


客户端
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ChatClient extends Frame{
/**
*
*/
private static final long serialVersionUID = 1L;
TextArea ta = null;
TextField tf = null;
StringBuffer sbf = null;
Integer clientID = 0;
String hostIP = "localhost";
Socket s =null;
DataOutputStream dos = null;
DataInputStream dis = null;
public boolean bConnected =false;

public ChatClient() {
ta = new TextArea();
tf =new TextField();
sbf = new StringBuffer();
initView();
}

public static void main(String args[]){
new ChatClient();
}

private void connect(){
try {
s = new Socket(hostIP,ChatServer.TCP_PORT);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
new Thread(new RecvThread()).start();
bConnected = true;
System.out.println("connect to server!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

private void disConnect(){//退出
try {
this.bConnected =false;
ChatServer.clients.remove(this);
System.out.println("bye!");
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public void initView(){
this.setLocation(300,300);
ta.setEditable(false);
this.add(ta,BorderLayout.CENTER);
this.add(tf,BorderLayout.SOUTH);
tf.addActionListener(new TFListener());
this.setSize(300, 300);
this.pack();
this.setResizable(false);
this.setVisible(true);
this.setTitle("客户端");
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
disConnect();
System.exit(0);
}
});
this.connect();
}

private class TFListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
System.out.println(e.getActionCommand());
try {
dos.writeUTF(tf.getText());
dos.flush();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
private class RecvThread implements Runnable{
String s = null;
public void run() {

while(bConnected){
try {
s = dis.readUTF();
ta.setText(ta.getText()+ s+"\r\n");
tf.setText("");
}catch(EOFException e){
e.printStackTrace();
}catch(SocketException e){
System.out.println("客户端退出了!");
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

 


服务器端
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ChatServer extends Frame{
/**
*
*/
private static final long serialVersionUID = 1L;
public static final int TCP_PORT = 6666;
public static int userID = 1;
TextArea ta =null;
Socket s = null;
ServerSocket ss =null;
StringBuffer text = null;
DataInputStream dis = null;
DataOutputStream dos =null;
boolean started = false;
public static List<Client> clients = new ArrayList<Client>();

public ChatServer(){
ta = new TextArea();
text = new StringBuffer();
initView();
}

private void initView(){
this.setSize(300,300);
this.setLocation(200,200);
this.setTitle("服务器");
ta.setEditable(false);
this.add(ta);
this.pack();
this.setVisible(true);
this.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.start();
}

public void start(){
System.out.println("Server Start!");
try {
ss = new ServerSocket(TCP_PORT);
started = true;
} catch(BindException e){
System.out.println("端口使用中....");
System.out.println("请关掉相关程序并重新运行服务器!");
System.exit(0);
}catch (IOException e){
e.printStackTrace();
}
try {
while(started){
s = ss.accept();
System.out.println("A client connected!");
Client c = new Client(s);
clients.add(c);
new Thread(c).start();
}
}catch (IOException e){
e.printStackTrace();
}finally{
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
new ChatServer();
}

protected class Client implements Runnable{
private int ID = 0;
private Socket s = null;
private DataInputStream dis = null;
private DataOutputStream dos =null;
private boolean bConnect= false;

public Client(Socket s){
this.s =s;
this.setID(userID++);
this.bConnect= true;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}

private void send(String str){
for(int i=0;i<clients.size();i++){
try {
clients.get(i).dos.writeUTF("用户" + ID+": " + str);
} catch (IOException e) {
e.printStackTrace();
}
}
}

public void run() {
try {
while(bConnect){
String str = dis.readUTF();
this.send(str);
}
}catch(EOFException e){
System.out.println("client disconnect!");
// e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}finally{
try {
clients.remove(this);
bConnect = false;
if(dis != null) dis.close();
if(dos != null) dos.close();
if(s != null) s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public int getID() {
return this.ID;
}

public void setID(int ID) {
this.ID = ID;
}
}
}

posted on 2014-10-09 21:04  Swift小强  阅读(350)  评论(0)    收藏  举报

导航