Creating a simple Chat Client/Server Solution – Part3

Standard

Step 3: Multi-Server handling Multi-Client (Client as before)

import java.net.*;
import java.io.*;

public class ChatServer implements Runnable
{  private ServerSocket     server = null;
private Thread           thread = null;
private ChatServerThread client = null;

public ChatServer(int port)
{  try
{  System.out.println(“Binding to port ” + port + “, please wait  …”);
server = new ServerSocket(port);
System.out.println(“Server started: ” + server);
start();
}
catch(IOException ioe)
{  System.out.println(ioe); }
}
public void run()
{  while (thread != null)
{  try
{  System.out.println(“Waiting for a client …”);
addThread(server.accept());
}
catch(IOException ie)
{  System.out.println(“Acceptance Error: ” + ie); }
}
}
public void addThread(Socket socket)
{  System.out.println(“Client accepted: ” + socket);
client = new ChatServerThread(this, socket);
try
{  client.open();
client.start();
}
catch(IOException ioe)
{  System.out.println(“Error opening thread: ” + ioe); }
}
public void start()                   { /* no change */ }
public void stop()                    { /* no change */ }
public static void main(String args[]){ /* no change */ }
}

import java.net.*;
import java.io.*;

public class ChatServerThread extends Thread
{  private Socket          socket   = null;
private ChatServer      server   = null;
private int             ID       = -1;
private DataInputStream streamIn =  null;

public ChatServerThread(ChatServer _server, Socket _socket)
{  server = _server;  socket = _socket;  ID = socket.getPort();
}
public void run()
{  System.out.println(“Server Thread ” + ID + ” running.”);
while (true)
{  try
{  System.out.println(streamIn.readUTF());
}
catch(IOException ioe) {  }
}
}
public void open() throws IOException
{  streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException
{  if (socket != null)    socket.close();
if (streamIn != null)  streamIn.close();
}
}

Nguồn: Sưu tầm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s