This problem has to be a pretty simple one, but I can't get it to work. I have a program that has a server accepting connections. I first made it single threaded, and in a moments ambition decided to make it multithreaded... I managed to get it working just fine, but now I noticed that it has to be single threaded! The problem is that the current transaction will affect the next one, so there can't be several at a time.
I've been trying to get it single threaded again, but I either have the server crashing or ending after the first connection. This is the working multithreaded server:
And the thread, which directs the package to a protocol that does all the work.
Would there be an easy way to change this back to a single threaded server? I've been tryinig to combine to two classes into one, but it just won't work out.
I've been trying to get it single threaded again, but I either have the server crashing or ending after the first connection. This is the working multithreaded server:
Code:
/**
* Server waiting for clients to connect. It starts a new thead for each connection
**/
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) {
ServerSocket serverSocket = null;
boolean listening = true;
// Listen to incoming connections
try {
serverSocket = new ServerSocket(7);
} catch (IOException e) {
System.err.println("Server, line 21. Could not listen on port: 7.");
System.exit(-1);
}
// The incoming connection is directed to it's own thread
while (listening) {
try {
new ServerThread(serverSocket.accept()).start();
}
catch (IOException e) {
System.out.println("Server, line 32");
}
}
// close the connection
try {
serverSocket.close();
} catch (IOException e) {
System.out.println("Server, rivi 41");
}
}
}
And the thread, which directs the package to a protocol that does all the work.
Code:
/**
* Directs the incoming packages to the protocol for further work, and returns the
* outcome to the client
**/
import java.net.*;
import java.io.*;
public class ServerThread extends Thread implements Serializable {
private Socket socket = null;
public ServerThread(Socket socket) {
super("Server");
this.socket=socket;
}
public void run() {
try {
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
TransferePackage inputLine, outputLine;
WorkProtocol dp = new WorkProtocol();
inputLine = null;
try {
inputLine=(Siirto)in.readObject();
} catch (ClassNotFoundException e) {
System.out.println(e);
}
outputLine = dp.processInput(inputLine);
out.writeObject(outputLine);
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Would there be an easy way to change this back to a single threaded server? I've been tryinig to combine to two classes into one, but it just won't work out.