i have coded a socket listener that should listen on port 80 and 81 and when data arrive on these ports execute operations on these data. I want this listener to concurrently listen on both these ports and hav coded in the following way.
import java.net.*;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class MultipleSocketServer implements Runnable {
private int a;
private ServerSocket connection;
private String TimeStamp;
private int ID;
public static void main(String[] args){
// System.out.print("ip");
// String gh="12345";
//System.out.println(gh.substring(1,3));
int port = 80;
int port1 = 81;
int count = 0;
double a=234.52121;
//System.out.println(bf3.toString());
try{
ServerSocket socket1 = new ServerSocket(port);
ServerSocket socket2=new ServerSocket(port1);
System.out.println("MultipleSocketServer Initialized");
Runnable runnable = new MultipleSocketServer(socket1, ++count);
Runnable run = new MultipleSocketServer(socket2, ++count);
Thread thread = new Thread(runnable);
Thread thread1 = new Thread(run);
while (true) {
//Socket connection = socket1.accept();
thread.start();
thread1.start();
}
}
catch (Exception e) {}
}
MultipleSocketServer(ServerSocket s, int i) {
this.connection = s;
this.ID = i;
}
public void run() {
while(true){
try {
Socket incoming=connection.accept();
BufferedInputStream is = new BufferedInputStream(incoming.getInputStream());
int character;
while((character = is.read())!=-1) {
.
.
do the input data handling here
.
.
}
}
catch(Exception e){}
}
}
}
But for some reason this does not seem to show the threaded/conncurrent behaviour.
I am testing this code using Hyperterminal, and every time i disconnect from hyperterminal, the program execution stops and "Socket is closed" exception is raised.
Any pointers would be of great help
Cheers
You're starting threads in an endless loop.
while (true) {
//Socket connection = socket1.accept();
thread.start();
thread1.start();
}
I think though, that this is handled (ignored) in
} catch (Exception e) {}
However, I suspect that the problem you describe is in in the handling code you didn't include. One pretty obvious idea: you don't call connection.close() instead of incoming.close(), do you?
Related
I'm currently developing a TicTacToe multithreaded networked game for my university and I'm stuck on an annoying problem.
I wish that my server accepts 2 connections each time and then waits for other 2 connections etc.
The problem is that, in my code, if a client connects to the server and closes the connection while the second client is not yet connected to the server, the second client is not able to play because it "thinks" that the first client is connected and ready.
I thought to do something like this but I can't find a way to actually implement it.
The server is structured in 3 classes:
TTT_Server (which cointains the main method and launches threads);
TTT_ServerThread (which contains the thread(s) behaviour);
TTT (which contains the TicTacToe board and some method).
TTT_Server class:
public class TTT_Server()
{
private static ServerSocket serverSocket;
private static boolean running = true;
public static void main(String[] args)
{
try
{
// creazione ServerSocket sulla porta 8089
serverSocket = new ServerSocket(8089);
System.out.println("Server Socket creata e in ascolto sulla porta 8089");
while(running)
{
TTT ttt = new TTT();
Socket socket1 = serverSocket.accept();
Socket socket2 = serverSocket.accept();
TTT_ServerThread st1 = new TTT_ServerThread(socket1, 1, ttt, socket2);
TTT_ServerThread st2 = new TTT_ServerThread(socket2, 2, ttt, socket1);
st1.start();
st2.start();
System.out.println("thread lanciati");
}
}
catch(IOException e)
{
System.out.println(e);
running = false;
}
finally
{
try
{
serverSocket.close();
}
catch (IOException e)
{
System.out.println(e);
}
}
}
}
(a part of) TTT_ServerThread class:
private Socket socket;
private Socket socketOtherPlayer;
private BufferedReader in;
private PrintWriter out;
private PrintWriter outOtherPlayer;
private TTT TicTacToe;
private int player;
private boolean fineGioco;
private int counter = 0;
public TTT_ServerThread(Socket socket, int num_connessione, TTT ttt, Socket socketOtherPlayer)
{
this.socket = socket;
this.socketOtherPlayer = socketOtherPlayer;
this.player = num_connessione;
this.TicTacToe = ttt;
try
{
this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.out = new PrintWriter(socket.getOutputStream());
this.outOtherPlayer= new PrintWriter(socketOtherPlayer.getOutputStream());
}
catch(IOException e)
{
System.out.println(e);
}
}
#Override
public void run()
{
//[...]
}
(a part of) TTT class:
public class TTT
{
private int[] board = new int[9];
private int turno = 1;
public TTT()
{
for (int i = 0; i < 9; i++)
board[i] = 0;
}
protected synchronized void setBoard(int locazioneMossa, int giocatore)
{
board[locazioneMossa] = giocatore;
}
protected synchronized int getBoard(int locazioneMossa)
{
return board[locazioneMossa];
}
protected synchronized void setTurno(int turnoRicevuto)
{
turno = turnoRicevuto;
}
protected synchronized int getTurno()
{
return turno;
}
//[...]
}
Is there a way to implement a sort of that diagram that i thought?
Thank you all in advance for the help! And sorry for my English, it's not my primary language.
Instead of trying to "accept two connections at a time", you should accept one connection at a time. If there's no waiting connection, the connection should be put to a waiting list. If there is a waiting connection, pair them up.
That way you'll have a single accept() per loop, but 2 possible ways to handle them.
I have written an app for port scanning and I want to write my console output to a file but a little problem occurred. "PrintStream" is not writing all console output to the file. For instance: code within try block which shows opened ports in the console does not write anything to the file, but dead hosts in catch block are written.
My code:
public class start {
public static void main(String[] args) throws IOException{
for (int i = 5935; i < 10000; i++){
new test(i);
}
PrintStream printStream = new PrintStream(new FileOutputStream("E:\\ports.txt"));
System.setOut(printStream);
printStream.flush();
}
}
class test implements Runnable{
static String host = "localhost";
int t;
Thread y;
public test(int t2){
t = t2;
y = new Thread(this);
y.start();
}
public void run() {
try {
Socket socket = new Socket(host, t);
System.out.println("Port is alive - " + t);
} catch (IOException e){
System.out.println("Port is dead... - " + t);
}
}
}
Close socket
Use Executor Service
Set output stream before writing output
Wait for all jobs to be ready
Flush output when ready
Close printStream
Results in:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class start
{
public static void main(String[] args) throws Exception {
try (PrintStream printStream = new PrintStream(new FileOutputStream("E:\\ports.txt"))) {
System.setOut(printStream);
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 5935; i < 10000; i++) {
final int port = i;
pool.execute(() -> {
try (Socket socket = new Socket("localhost", port)) {
System.out.println("Port is alive - " + port);
}
catch (IOException e) {
System.out.println("Port is dead... - " + port);
}
});
}
pool.awaitTermination(100, TimeUnit.SECONDS);
printStream.flush();
}
}
}
You have a few issues directly related to the issue at hand.
You set the output AFTER you have started the threads so where the output goes is almost random.
You don't wait for the threads to finish, so the application "just ends" at a random point.
You don't flush the output.
Updated code:
class StartPortTester {
public static void main(String[] args) throws IOException, InterruptedException {
// Set up the stream BEFORE starting threads
// This should be in a try-with-resources, or the close done in a finally block.
PrintStream printStream = new PrintStream(new FileOutputStream("ports.txt"));
System.setOut(printStream);
// Start the threads!
List<PortTester> testers = new LinkedList<>();
for (int i = 5935; i < 10000; i++){
testers.add(new PortTester(i));
}
// Wait for the threads to end
for(PortTester t : testers ) {
t.y.join();
}
// Flush (write to disk) and close.
printStream.flush();
printStream.close();;
}
}
class PortTester implements Runnable{
static String host = "localhost";
int t;
Thread y;
public PortTester(int t2){
t = t2;
y = new Thread(this);
y.start();
}
public void run() {
try {
// You should close this either in the finally block or using a try-with-resource.
Socket socket = new Socket(host, t);
System.out.println("Port is alive - " + t);
} catch (IOException e){
System.out.println("Port is dead... - " + t);
}
}
}
This is not perfect as
it creates a ton of threads andit would be much better to use a thread pool.
It also waits forever for the thread to finish, you might want it to only wait x seconds before giving up.
Exceptions would cause the file to not be flushed & closed.
You mix up presentation with logic. I'd NOT write System.out in the PortTester, but create a data structure describing the ports statuses and then output that after (separate presentation from logic).
At the moment the ordering of the output is random (based on when the threads finish).
I have a server class which connects a client on a specific server socket port and starts off a thread with a service class. Specifically, I have 3 service classes so I would like to have 3 different ports. This however, is not working as I had expected it to. This is my code for the server:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
public class WebsiteServer {
public static void main(String args[]) throws IOException {
ServerSocket serversocket = new ServerSocket(22401);
ServerSocket serversocket2 = new ServerSocket(22402);
Thread thread;
Thread thread2;
Socket socket;
Socket socket2;
NewUserService newuserservice;
ExistingUserService existinguserservice;
System.out.println("Waiting for clients to connect.");
while (true) {
socket = serversocket.accept();
socket2 = serversocket2.accept();
if(socket.isConnected()) {
System.out.println("NewUserClient has connected.");
newuserservice = new NewUserService(socket);
thread = new Thread(newuserservice);
thread.start();
}
if(socket2.isConnected()) {
System.out.println("ExistingUserClient has connected.");
existinguserservice = new ExistingUserService(socket2);
thread2 = new Thread(existinguserservice);
thread2.start();
}
}
}
}
It works fine if I only use one port for example:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
public class WebsiteServer {
public static void main(String args[]) throws IOException {
ServerSocket serversocket = new ServerSocket(22401);
ServerSocket serversocket2 = new ServerSocket(22402);
Thread thread;
Thread thread2;
Socket socket;
Socket socket2;
NewUserService newuserservice;
ExistingUserService existinguserservice;
System.out.println("Waiting for clients to connect.");
while (true) {
socket = serversocket.accept();
//socket2 = serversocket2.accept();
if(socket.isConnected()) {
System.out.println("NewUserClient has connected.");
newuserservice = new NewUserService(socket);
thread = new Thread(newuserservice);
thread.start();
}
// if(socket2.isConnected()) {
//
// System.out.println("ExistingUserClient has connected.");
// existinguserservice = new ExistingUserService(socket2);
// thread2 = new Thread(existinguserservice);
// thread2.start();
// }
}
}
}
Any help would be appreciated.
The accept method blocks until a connection is made. So, you are sitting blocked one one .accept(), even though the other server may have activity. One simple solution would be to make one listening thread per server.
accept()is a blocking method. In other words, the second accept() is waiting for another connection. Untik a second connection is accepted, your code will be blocked
You need to call the accept() method in a separate thread. accept() blocks the thread until someone joins the server. This could be 1 ms or 1 year.
I suggest you create an AcceptListener to be called when someone joins
public interface AcceptListener{
public void socketAccepted(Socket s);
}
And a handler class
public class MyServerSocket extends Thread{
private AcceptListener l;
private boolean run = true;
private ServerSocket s;
public MyServerSocket(AcceptListener l, int port){
this.l = l;
this.s = new ServerSocket(port);
this.start();
}
public void run(){
while(run){
l.socketAccepted(s.accept());
}
}
}
You'll have to handle errors and whatnot and make the overrides in you subclass(es) of AcceptListener.
In my main thread I have a while(listening) loop which calls accept() on my ServerSocket object, then starts a new client thread and adds it to a Collection when a new client is accepted.
I also have an Admin thread which I want to use to issue commands, like 'exit', which will cause all the client threads to be shut down, shut itself down, and shut down the main thread, by turning listening to false.
However, the accept() call in the while(listening) loop blocks, and there doesn't seem to be any way to interrupt it, so the while condition cannot be checked again and the program cannot exit!
Is there a better way to do this? Or some way to interrupt the blocking method?
You can call close() from another thread, and the accept() call will throw a SocketException.
Set timeout on accept(), then the call will timeout the blocking after specified time:
http://docs.oracle.com/javase/7/docs/api/java/net/SocketOptions.html#SO_TIMEOUT
Set a timeout on blocking Socket operations:
ServerSocket.accept();
SocketInputStream.read();
DatagramSocket.receive();
The option must be set prior to entering a blocking operation to take effect. If the timeout expires and the operation would continue to block, java.io.InterruptedIOException is raised. The Socket is not closed in this case.
Is calling close() on the ServerSocket an option?
http://java.sun.com/j2se/6/docs/api/java/net/ServerSocket.html#close%28%29
Closes this socket. Any thread currently blocked in accept() will throw a SocketException.
You can just create "void" socket for break serversocket.accept()
Server side
private static final byte END_WAITING = 66;
private static final byte CONNECT_REQUEST = 1;
while (true) {
Socket clientSock = serverSocket.accept();
int code = clientSock.getInputStream().read();
if (code == END_WAITING
/*&& clientSock.getInetAddress().getHostAddress().equals(myIp)*/) {
// End waiting clients code detected
break;
} else if (code == CONNECT_REQUEST) { // other action
// ...
}
}
Method for break server cycle
void acceptClients() {
try {
Socket s = new Socket(myIp, PORT);
s.getOutputStream().write(END_WAITING);
s.getOutputStream().flush();
s.close();
} catch (IOException e) {
}
}
The reason ServerSocket.close() throws an exception
is because you have an outputstream or an inputstream
attached to that socket.
You can avoid this exception safely by first closing the input and output streams.
Then try closing the ServerSocket.
Here is an example:
void closeServer() throws IOException {
try {
if (outputstream != null)
outputstream.close();
if (inputstream != null)
inputstream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
if (!serversock.isClosed())
serversock.close();
}
}
You can call this method to close any socket from anywhere without getting an exception.
Use serverSocket.setSoTimeout(timeoutInMillis).
OK, I got this working in a way that addresses the OP's question more directly.
Keep reading past the short answer for a Thread example of how I use this.
Short answer:
ServerSocket myServer;
Socket clientSocket;
try {
myServer = new ServerSocket(port)
myServer.setSoTimeout(2000);
//YOU MUST DO THIS ANYTIME TO ASSIGN new ServerSocket() to myServer‼!
clientSocket = myServer.accept();
//In this case, after 2 seconds the below interruption will be thrown
}
catch (java.io.InterruptedIOException e) {
/* This is where you handle the timeout. THIS WILL NOT stop
the running of your code unless you issue a break; so you
can do whatever you need to do here to handle whatever you
want to happen when the timeout occurs.
*/
}
Real world example:
In this example, I have a ServerSocket waiting for a connection inside a Thread. When I close the app, I want to shut down the thread (more specifically, the socket) in a clean manner before I let the app close, so I use the .setSoTimeout() on the ServerSocket then I use the interrupt that is thrown after the timeout to check and see if the parent is trying to shut down the thread. If so, then I set close the socket, then set a flag indicating that the thread is done, then I break out of the Threads loop which returns a null.
package MyServer;
import javafx.concurrent.Task;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import javafx.concurrent.Task;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class Server {
public Server (int port) {this.port = port;}
private boolean threadDone = false;
private boolean threadInterrupted = false;
private boolean threadRunning = false;
private ServerSocket myServer = null;
private Socket clientSocket = null;
private Thread serverThread = null;;
private int port;
private static final int SO_TIMEOUT = 5000; //5 seconds
public void startServer() {
if (!threadRunning) {
serverThread = new Thread(thisServerTask);
serverThread.setDaemon(true);
serverThread.start();
}
}
public void stopServer() {
if (threadRunning) {
threadInterrupted = true;
while (!threadDone) {
//We are just waiting for the timeout to exception happen
}
if (threadDone) {threadRunning = false;}
}
}
public boolean isRunning() {return threadRunning;}
private Task<Void> thisServerTask = new Task <Void>() {
#Override public Void call() throws InterruptedException {
threadRunning = true;
try {
myServer = new ServerSocket(port);
myServer.setSoTimeout(SO_TIMEOUT);
clientSocket = new Socket();
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
try {
clientSocket = myServer.accept();
}
catch (java.io.InterruptedIOException e) {
if (threadInterrupted) {
try { clientSocket.close(); } //This is the clean exit I'm after.
catch (IOException e1) { e1.printStackTrace(); }
threadDone = true;
break;
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
};
}
Then, in my Controller class ... (I will only show relevant code, massage it into your own code as needed)
public class Controller {
Server server = null;
private static final int port = 10000;
private void stopTheServer() {
server.stopServer();
while (server.isRunning() {
//We just wait for the server service to stop.
}
}
#FXML private void initialize() {
Platform.runLater(()-> {
server = new Server(port);
server.startServer();
Stage stage = (Stage) serverStatusLabel.getScene().getWindow();
stage.setOnCloseRequest(event->stopTheServer());
});
}
}
I hope this helps someone down the road.
Another thing you can try which is cleaner, is to check a flag in the accept loop, and then when your admin thread wants to kill the thread blocking on the accept, set the flag (make it thread safe) and then make a client socket connection to the listening socket.
The accept will stop blocking and return the new socket.
You can work out some simple protocol thing telling the listening thread to exit the thread cleanly.
And then close the socket on the client side.
No exceptions, much cleaner.
You can simply pass the timeout limit (milli seconds) as a parameter while calling accept function.
eg serverSocket.accept(1000);
automatically close the request after 1 sec
I am working on a java program that is essentially a chat room. This is an assignment for class so no code please, I am just having some issues determining the most feasible way to handle what I need to do. I have a server program already setup for a single client using threads to get the data input stream and a thread to handle sending on the data output stream. What I need to do now is create a new thread for each incoming request.
My thought is to create a linked list to contain either the client sockets, or possibly the thread. Where I am stumbling is figuring out how to handle sending the messages out to all the clients. If I have a thread for each incoming message how can I then turn around and send that out to each client socket.
I'm thinking that if I had a linkedlist of the clientsockets I could then traverse the list and send it out to each one, but then I would have to create a dataoutputstream each time. Could I create a linkedlist of dataoutputstreams? Sorry if it sounds like I'm rambling but I don't want to just start coding this, it could get messy without a good plan. Thanks!
EDIT
I decided to post the code I have so far. I haven't had a chance to test it yet so any comments would be great. Thanks!
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.LinkedList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class prog4_server {
// A Queue of Strings used to hold out bound Messages
// It blocks till on is available
static BlockingQueue<String> outboundMessages = new LinkedBlockingQueue<String>();
// A linked list of data output streams
// to all the clients
static LinkedList<DataOutputStream> outputstreams;
// public variables to track the number of clients
// and the state of the server
static Boolean serverstate = true;
static int clients = 0;
public static void main(String[] args) throws IOException{
//create a server socket and a clientSocket
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(6789);
} catch (IOException e) {
System.out.println("Could not listen on port: 6789");
System.exit(-1);
}// try{...}catch(IOException e){...}
Socket clientSocket;
// start the output thread which waits for elements
// in the message queue
OutputThread out = new OutputThread();
out.start();
while(serverstate){
try {
// wait and accept a new client
// pass the socket to a new Input Thread
clientSocket = serverSocket.accept();
DataOutputStream ServerOut = new DataOutputStream(clientSocket.getOutputStream());
InputThread in = new InputThread(clientSocket, clients);
in.start();
outputstreams.add(ServerOut);
} catch (IOException e) {
System.out.println("Accept failed: 6789");
System.exit(-1);
}// try{...}catch{..}
// increment the number of clients and report
clients = clients++;
System.out.println("Client #" + clients + "Accepted");
}//while(serverstate){...
}//public static void main
public static class OutputThread extends Thread {
//OutputThread Class Constructor
OutputThread() {
}//OutputThread(...){...
public void run() {
//string variable to contain the message
String msg = null;
while(!this.interrupted()) {
try {
msg = outboundMessages.take();
for(int i=0;i<outputstreams.size();i++){
outputstreams.get(i).writeBytes(msg + '\n');
}// for(...){...
} catch (IOException e) {
System.out.println(e);
} catch (InterruptedException e){
System.out.println(e);
}//try{...}catch{...}
}//while(...){
}//public void run(){...
}// public OutputThread(){...
public static class InputThread extends Thread {
Boolean threadstate = true;
BufferedReader ServerIn;
String user;
int threadID;
//SocketThread Class Constructor
InputThread(Socket clientSocket, int ID) {
threadID = ID;
try{
ServerIn = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
user = ServerIn.readLine();
}
catch(IOException e){
System.out.println(e);
}
}// InputThread(...){...
public void run() {
String msg = null;
while (threadstate) {
try {
msg = ServerIn.readLine();
if(msg.equals("EXITEXIT")){
// if the client is exiting close the thread
// close the output stream with the same ID
// and decrement the number of clients
threadstate = false;
outputstreams.get(threadID).close();
outputstreams.remove(threadID);
clients = clients--;
if(clients == 0){
// if the number of clients has dropped to zero
// close the server
serverstate = false;
ServerIn.close();
}// if(clients == 0){...
}else{
// add a message to the message queue
outboundMessages.add(user + ": " + msg);
}//if..else...
} catch (IOException e) {
System.out.println(e);
}// try { ... } catch { ...}
}// while
}// public void run() { ...
}
public static class ServerThread extends Thread {
//public variable declaration
BufferedReader UserIn =
new BufferedReader(new InputStreamReader(System.in));
//OutputThread Class Constructor
ServerThread() {
}//OutputThread(...){...
public void run() {
//string variable to contain the message
String msg = null;
try {
//while loop will continue until
//exit command is received
//then send the exit command to all clients
msg = UserIn.readLine();
while (!msg.equals("EXITEXIT")) {
System.out.println("Enter Message: ");
msg = UserIn.readLine();
}//while(...){
outboundMessages.add(msg);
serverstate = false;
UserIn.close();
} catch (IOException e) {
System.out.println(e);
}//try{...}catch{...}
}//public void run(){...
}// public serverThread(){...
}// public class prog4_server
I have solved this problem in the past by defining a "MessageHandler" class per client connection, responsible for inbound / outbound message traffic. Internally the handler uses a BlockingQueue implementation onto which outbound messages are placed (by internal worker threads). The I/O sender thread continually attempts to read from the queue (blocking if required) and sends each message retrieved to the client.
Here's some skeleton example code (untested):
/**
* Our Message definition. A message is capable of writing itself to
* a DataOutputStream.
*/
public interface Message {
void writeTo(DataOutputStream daos) throws IOException;
}
/**
* Handler definition. The handler contains two threads: One for sending
* and one for receiving messages. It is initialised with an open socket.
*/
public class MessageHandler {
private final DataOutputStream daos;
private final DataInputStream dais;
private final Thread sender;
private final Thread receiver;
private final BlockingQueue<Message> outboundMessages = new LinkedBlockingQueue<Message>();
public MessageHandler(Socket skt) throws IOException {
this.daos = new DataOutputStream(skt.getOutputStream());
this.dais = new DataInputStream(skt.getInputStream());
// Create sender and receiver threads responsible for performing the I/O.
this.sender = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
Message msg = outboundMessages.take(); // Will block until a message is available.
try {
msg.writeTo(daos);
} catch(IOException ex) {
// TODO: Handle exception
}
}
}
}, String.format("SenderThread-%s", skt.getRemoteSocketAddress()));
this.receiver = new Thread(new Runnable() {
public void run() {
// TODO: Read from DataInputStream and create inbound message.
}
}, String.format("ReceiverThread-%s", skt.getRemoteSocketAddress()));
sender.start();
receiver.start();
}
/**
* Submits a message to the outbound queue, ready for sending.
*/
public void sendOutboundMessage(Message msg) {
outboundMessages.add(msg);
}
public void destroy() {
// TODO: Interrupt and join with threads. Close streams and socket.
}
}
Note that Nikolai is correct in that blocking I/O using 1 (or 2) threads per connection is not a scalable solution and typically applications might be written using Java NIO to get round this. However, in reality unless you're writing an enterprise server which thousands of clients connect to simultaneously then this isn't really an issue. Writing bug-free scalable applications using Java NIO is difficult and certainly not something I'd recommend.