import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
public class Chat_Server {
ServerSocket server=null;
//ObjectInputStream input=null;
boolean isStart=false;//服务端是否启动
boolean isConnect=false;//客户端是否连接上
ArrayList
new ArrayList
public static void main(String[] args) {
new Chat_Server().startServer();
}
private void startServer(){
System.out.println("服务端已启动");
try{
server=new ServerSocket(8888);
isStart=true;
}catch(BindException e){
System.out.println("端口使用中....");
System.exit(0);
}catch(IOException e){
e.printStackTrace();
System.exit(0);
}
try {
while(isStart){
Socket client=server.accept();
//客户端连接成功后,为客户端创建一个独立的线程接受消息
Client_Thread client_thread=
new Client_Thread(client);
new Thread(client_thread).start();//启动线程
clients.add(client_thread);//添加
}
}catch(Exception e){
e.printStackTrace();
}
finally{
try {
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* 每当一个客户端连接到服务器都会创建一个如此的线程
*/
class Client_Thread implements Runnable{
//类里边保留socket、inputStream
private Socket s=null;
private ObjectInputStream in=null;
private ObjectOutputStream output=null;
private boolean isConnect=false;
Client_Thread(Socket s){
this.s=s;
try {
in=new ObjectInputStream(s.getInputStream());
output=new ObjectOutputStream(s.getOutputStream());
isConnect=true;
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Client_Thread");
e.printStackTrace();
}
}
public void send(String str){
try {
output.writeObject(str);
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
System.out.println("服务端监听已启动");
String str;
try {
while(isConnect){
str = (String)in.readObject();
System.out.println(str);
for(int i=0;i
c.send(str);
}
}
} catch (SocketException e) {
System.out.println("客户端已关闭");
} catch (Exception e) {
// TODO Auto-generated catch bl