Server:
import java.net.*;
import java.io.*;
import java.util.*;
public class Server extends ServerSocket {
private Socket socket;
private static final int SERVER_PORT = 6789;
private static ArrayList User_List = new ArrayList();
private static ArrayList Threader = new ArrayList();
private static LinkedList Message_Array = new LinkedList();
private static int Thread_Counter = 0;
private static boolean isClear = true;
protected FileOutputStream LOG_FILE = new FileOutputStream("E:/program/connect.log",true);
public Server() throws IOException,FileNotFoundException
{
super(SERVER_PORT);
new Broadcast();
Calendar now = Calendar.getInstance();
String str = "[" + now.getTime().toString() + " ] Accepted a connection1512";
byte[] tmp = str.getBytes();
LOG_FILE.write(tmp);
try
{
while(true)
{
socket = accept();
new CreateServerThread(socket);
}
}
catch(IOException e)
{}
finally
{
close();
}
}
class Broadcast extends Thread
{
public Broadcast()
{
start();
}
public void run()
{
while(true)
{
if(!isClear)
{
String tmp = (String)Message_Array.getFirst();
for(int i = 0; i< Threader.size();i++)
{
CreateServerThread client = (CreateServerThread)Threader.get(i);
client.SendMessage(tmp);
}
Message_Array.removeFirst();
isClear = Message_Array.size()>0 ? false:true;
}
}
}
}
class CreateServerThread extends Thread
{
private Socket client;
private BufferedReader in;
private PrintWriter out;
private String username;
public CreateServerThread(Socket s) throws IOException
{
client = s;
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(),true);
out.println("--Welcome to this chatroom--");
out.println("input your nickname:");
start();
}
public void SendMessage(String msg)
{
out.println(msg);
}
public void run()
{
try
{
int flag = 0;
Thread_Counter++;
String line = in.readLine();
while(!line.equals("bye"))
{
if(line.equals("1"))
{
out.println(ListOnlineUsers());
line = in.readLine();
continue;
}
if(flag++ == 0)
{
username = line;
User_List.add(username);
out.println(ListOnlineUsers());
Threader.add(this);
PushMessage("[< "+username+" come on in >]");
}
else
{
PushMessage("< "+ username + " >" + line);
}
line = in.readLine();
}
out.println("--see you,bye--");
client.close();
}
catch(IOException e)
{}
finally
{
try
{
client.close();
}
catch(IOException e)
{}
Thread_Counter --;
Threader.remove(this);
User_List.remove(username);
PushMessage("[< " + username + " left>]" );
}
}
private String ListOnlineUsers()
{
String s = "-+- Online list -+-1512";
for (int i = 0 ; i < User_List.size(); i ++)
{
s+="[" + User_List.get(i) + "]1512";
}
s+="-+-----------------------+-";
return s;
}
private void PushMessage(String msg)
{
Message_Array.addLast(msg);
isClear = false;
}
}
/**
* @param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
new Server();
}
}
Client:
same as single client