日期:2014-05-17 浏览次数:20940 次
import java.net.*;
import java.net.*;
import java.io.*;
public class Server{
private final int maxClientCount = 10;
private int clientNum = 0;
private ServerSocket ss;
private ChatThread communicationThread[];
public Server(){
//创建ServerSocket,允许10人在线
try{
ss = new ServerSocket(10000,maxClientCount);
}
catch(IOException e){
System.err.println(e.toString());
System.exit(1);
}
communicationThread = new ChatThread[maxClientCount];
//循环等待用户连接
for(int i=0;i<maxClientCount;i++){
try{
communicationThread[i] = new ChatThread(ss.accept(),i); //连接成功时启动它
communicationThread[i].start();
clientNum++;
}
catch(IOException e){
System.err.println(e.toString());
System.exit(1);
}
}
}
//线程类
private class ChatThread extends Thread{
private Socket socket;
private int clientID;
private DataInputStream br;
private DataOutputStream bw;
public ChatThread(Socket socket,int number){
this.socket = socket;
clientID = number;
try{
//从socket获得输入流和输出流
br = new DataInputStream(socket.getInputStream());
bw = new DataOutputStream(socket.getOutputStream());
}
catch(IOException e){
System.err.println(e.toString());
System.exit(1);
}
}
//run()方法
public void run(){
try{
bw.writeInt(clientID);
}
catch(IOException e){
System.err.println(e.toString());
System.exit(1);
}
//循环读一用户的信息,并把它发送给其他用户
while(true){
try{
//读对应的用户发送过来的信息
String message = br.readUTF();
//发送给其他用户
for(int i=0;i<clientNum;i++){
communicationThread[i].bw.writeUTF("客户" + clientID + ":" + message);
}
if(message != null && message.equals("bye"))
break;
}
catch(IOException e){
System.err.println(e.toString());
System.exit(1);
}
}
try{
bw.close();
br.close();
socket.close();
}
catch(EOFException e){
System.err.println(e.toString());
}
catch(IOException e){
System.err.println(e.toString());
}
}
}
public static void main(String args[]){
new Server();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class Client extends JFrame implements Runnable{
private int clientID;
private String clientWord;
private JPanel topPanel;
private JLabel nameLabel;
private JTextField wordField;
private JButton submit;
private JTextArea displayField;
private Socket socket;
private DataInputStream br;
private DataOutputStream bw;
//