Java ServerSocket only accepts 2 connections - java

Right now I am playing a little arround with Client-Server application for example to communicate via a java application with a raspberry pi which runs a server application.
Well by this I found a problem and I dont find a possible solution. Using the following code I can connect twice to server but after 2 connects it will not accept any more connections. For example I start the Client the first time, and it works everything nicely. Then I close the client and start it again and it works again. But if I close it and start it a 3rd time, it will do nothing. The server will not accept the connection. I tried it with different pcs in my private network but never got a 3rd connection running.
Here is the Code I am running on the server:
public class Receiver {
private final Logger logger = Logger.getLogger(this.getClass().getName());
private ServerSocket serverSocket;
private boolean isRunning;
public Receiver(int port) {
isRunning = true;
try {
serverSocket = new ServerSocket(port);
logger.log(Level.FINER, "start listening at port " + port);
logger.log(Level.FINER, "established successful.");
} catch (IOException e) {
logger.log(Level.SEVERE, "Error while opening socket:\n" + LogUtil.getStackTrace(e));
System.exit(1);
}
}
/**
* server starts to listen at the specific port
*/
public void listenServer() {
logger.log(Level.FINER, "Server is listening");
while (isRunning) {
try {
final Socket clientsocket = serverSocket.accept();
logger.log(Level.FINER, "Server accepted Connection from " + clientsocket.getInetAddress());
new Thread(new Runnable() {
#Override
public void run() {
handleConnection(clientsocket);
}
}).start();
} catch (IOException e) {
logger.log(Level.SEVERE, "Connection with Client failed.");
}
}
}
/**
* handles the given connection
*
* #param clientSocket
* the given client socket for this connection
*/
private void handleConnection(Socket clientSocket) {
ObjectInputStream instream = null;
ObjectOutputStream outstream = null;
try {
outstream = new ObjectOutputStream(clientSocket.getOutputStream());
instream = new ObjectInputStream(clientSocket.getInputStream());
final RequestProcessor processor = new RequestProcessor();
final InetAddress inetAdress = clientSocket.getInetAddress();
logger.log(Level.FINER, "handle connection from " + inetAdress);
Object inob;
while ((inob = instream.readObject()) != null) {
logger.log(Level.FINER, "received Object from " + inetAdress);
final ObjectOutputStream finalOutputStream = outstream;
final Object finalInob = inob;
new Thread() {
public void run() {
setPriority(MAX_PRIORITY);
Object outob;
try {
outob = processor.processObject(finalInob);
logger.log(Level.FINER, "send Respond to: " + inetAdress + " Error: " + (outob instanceof ErrorMessage));
finalOutputStream.writeObject(outob);
finalOutputStream.flush();
} catch (IOException e) {
logger.log(Level.SEVERE, "Connection closed to " + inetAdress);
}
}
}.start();
}
closeConnection(clientSocket, instream, outstream);
} catch (IOException e) {
logger.log(Level.SEVERE, "Connection closed to " + clientSocket.getInetAddress());
} catch (ClassNotFoundException e) {
logger.log(Level.SEVERE, "Connection closed to " + clientSocket.getInetAddress());
} finally {
closeConnection(clientSocket, instream, outstream);
}
}
/**
* closes InputStream, OutputStream and socket
*
* #param socket
* #param instream
* #param outstream
*/
private void closeConnection(Socket socket, InputStream instream, OutputStream outstream) {
this.isRunning = false;
if (instream != null) {
try {
instream.close();
} catch (IOException e) {
}
}
if (outstream != null) {
try {
outstream.close();
} catch (IOException e) {
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
logger.log(Level.FINER, "Connection was closed to client " + socket.getInetAddress());
}
/**
* closes all connections and ends the server
*/
public void endAllConnections() {
this.isRunning = false;
if (this.serverSocket != null)
try {
this.serverSocket.close();
} catch (IOException e) {
// do nothing
}
}
}
and here is the client code which I am using to connect to this server:
public class SocketConnector implements IConnector {
private final Logger logger = Logger.getLogger(this.getClass().getName());
private Socket s;
private ObjectOutputStream oos;
private ObjectInputStream ois;
/**
* creates a new connection
*
* #param host
* given host
* #param port
* given port
*
* #throws UnknownHostException
* #throws IOException
*/
public SocketConnector(String host, int port) throws UnknownHostException, IOException {
logger.log(Level.FINER, "Establish connection to " + host + ":" + port);
s = new Socket(host, port);
oos = new ObjectOutputStream(s.getOutputStream());
ois = new ObjectInputStream(s.getInputStream());
}
// some methos which use oos and ois.
Does someone maybe know why the server does not accept any more connections when 2 clients connected and disconnected from it? I googled alot arround but didn't find an adequate answer :/
The server log says it doesn't even accept the new connection.
Thanks in advance :)

The situation is:
when calling final Socket clientsocket = serverSocket.accept(); the first time, it's waiting for the first client. when the first client connected, you pass this client to a thread then continue the loop that calls final Socket clientsocket = serverSocket.accept(); the second time. Since starting a thread take more time than going to the next loop, isRunning still is true. In handleConnection(Socket clientSocket), you call closeConnection(clientSocket, instream, outstream); which set isRunning to false. That is the point. When the second client connected, you also pass this client to another thread, then continue the loop where isRunning is false, so the loop is terminated. Hence, you can't get to the third client.

Related

Java Proxy Socket not connecting to client

I will post my code below, a little background.
I am trying to connect to a gameserver on port 9339. my local port changes each time. The aim is to pass the packets through the proxy and display the info in the command line.
The client connects to the remote host using bluestacks which is running the game.
Code:
import java.io.*;
import java.net.*;
public class proxy {
public static void main(String[] args) throws IOException {
try {
String host = "gamea.clashofclans.com";
int remoteport = 9339;
ServerSocket ss = new ServerSocket(0);
int localport = ss.getLocalPort();
ss.setReuseAddress(true);
// Print a start-up message
System.out.println("Starting proxy for " + host + ":" + remoteport
+ " on port " + localport);
// And start running the server
runServer(host, remoteport, localport,ss); // never returns
System.out.println("Started proxy!");
} catch (Exception e) {
System.err.println(e);
}
}
/**
* runs a single-threaded proxy server on
* the specified local port. It never returns.
*/
public static void runServer(String host, int remoteport, int localport, ServerSocket ss)
throws IOException {
final byte[] request = new byte[2048];
byte[] reply = new byte[4096];
while (true) {
Socket client = null, server = null;
try {
// Wait for a connection on the local port
client = ss.accept();
System.out.println("Client Accepted!");
final InputStream streamFromClient = client.getInputStream();
final OutputStream streamToClient = client.getOutputStream();
// Make a connection to the real server.
// If we cannot connect to the server, send an error to the
// client, disconnect, and continue waiting for connections.
try {
server = new Socket(host, remoteport);
System.out.println("Client connected to server.");
} catch (IOException e) {
PrintWriter out = new PrintWriter(streamToClient);
out.print("Proxy server cannot connect to " + host + ":"
+ remoteport + ":\n" + e + "\n");
out.flush();
client.close();
System.out.println("Client disconnected");
continue;
}
// Get server streams.
final InputStream streamFromServer = server.getInputStream();
final OutputStream streamToServer = server.getOutputStream();
// a thread to read the client's requests and pass them
// to the server. A separate thread for asynchronous.
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
while ((bytesRead = streamFromClient.read(request)) != -1) {
streamToServer.write(request, 0, bytesRead);
streamToServer.flush();
}
} catch (IOException e) {
}
// the client closed the connection to us, so close our
// connection to the server.
try {
streamToServer.close();
} catch (IOException e) {
}
}
};
// Start the client-to-server request thread running
t.start();
// Read the server's responses
// and pass them back to the client.
int bytesRead;
try {
while ((bytesRead = streamFromServer.read(reply)) != -1) {
streamToClient.write(reply, 0, bytesRead);
streamToClient.flush();
}
} catch (IOException e) {
}
// The server closed its connection to us, so we close our
// connection to our client.
streamToClient.close();
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (server != null)
server.close();
if (client != null)
client.close();
} catch (IOException e) {
}
}
}
}
}
Basically the last thing that is printed out is "Starting proxy for gamea.clashofclans.com:9339 on port (whatever it chose).
Hopefully someone can help me.
I have this problem too, I don`t have enough time to correct this but i think using thread is that is why all mistake.
check your proxy for working on browser setting( May be proxy had problem)
If not,
I suggest to don`t use thread. maybe mutual exclusion occurs.
Your code is correct.It is working fine so you don't need any fix. What is happening is , your serverSocket in your proxy class is waiting for client to connect. that's why it is not going forward. What you need to do is, create a client and connect to it.
follow the step :
run your proxy.
then run your client
for the client, you can use this code,
public static void main(String[] args) throws IOException {
try {
int remoteport = 9339;
String host="127.0.0.1";
makeConnection(host, remoteport);
System.out.println("connection successful!");
} catch (Exception e) {
System.err.println(e);
}
}
public static void makeConnection(String host, int remoteport) throws IOException {
while (true) {
Socket client = null;
try {
client = new Socket(host, remoteport);
System.out.println("Client connected to server.");
break;
} catch (IOException e) {
System.err.println(e);
} finally {
if (client != null)
client.close();
if (client != null)
client.close();
}
}
}

Using a Handler to pass Object to the UI thread in order to make some UI updates

I have this client class "T_Client" in a client-server implementation
T_Client:
public class T_Client{
private static final String TAG = "T_Client";
private static String serverIP = "192.168.2.5";
private static int port = 4444;
private InetAddress serverAddr = null;
private Socket sock = null;
private boolean running = false;
private ObjectInputStream in;
private ObjectOutputStream out;
Object objIn;
public void send(MessageCustom _msg) {
if (out != null) {
try {
out.writeObject(_msg);
out.flush();
// out.close();
Log.i("Send Method", "Outgoing : " + _msg.toString());
} catch (IOException ex) {
Log.e("Send Method", ex.toString());
}
}
}
public void stopClient() {
running = false;
}
public void run() {
running = true;
try {
// here you must put your computer's IP address.
serverAddr = InetAddress.getByName(serverIP);
Log.i("TCP Client", "C: Connecting...");
// create a socket to make the connection with the server
sock = new Socket(serverAddr, port);
try {
// send the message to the server
out = new ObjectOutputStream(sock.getOutputStream());
// receive the message which the server sends back
in = new ObjectInputStream(sock.getInputStream());
Log.i("TCP Client", "C: Connected.");
// in this while the client listens for the messages sent by the
// server
while (running) {
objIn = in.readObject();
Log.i("Object Read", objIn.toString());
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + objIn
+ "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
// the socket must be closed. It is not possible to reconnect to
// this socket
// after it is closed, which means a new socket instance has to
// be created.
out.close();
in.close();
sock.close();
Log.i(TAG, "Closing socket: " + sock);
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
}
And I want to get the Object from the server(objIn) and pass it to the UI thread so I can do some UI updates there. From searching around a bit, I think that I have to use a Handler, but can't really wrap my head around the implementation.
Could someone give me a simple example of how to implement a handler in my case, and make the call in a Main Activity? Or point me to a simple tutorial to get me started, cause I've tried to follow the one over at the Android Developers site but it's too complicated.

TCP Server-Server communication

I'm developing an Android application (client) and want it to connect with my Java server using TCP communication, and so far everything is going well.
Server Code:
import java.net.*;
import java.io.*;
import globalvariables.GlobalVariables;
import interface_package.ServerInterface;
import java.util.Timer;
/**
*
* #author wsserver
*/
public class ThreadedAndroidServer {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
GlobalVariables.init();
//Prevzemi staticen interface
GlobalVariables.sinterface = new ServerInterface();
GlobalVariables.sinterface.show();
//INFINITE LOOP
while(true)
int port = GlobalVariables.portNo;
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
System.out.println("Server has started listening on port " + port);
GlobalVariables.sinterface.setServerStatus("Server has started listening on port " + port);
} catch (IOException e) {
System.out.println("Error: Cannot listen on port " + port + " : " + e);
GlobalVariables.sinterface.setServerStatus("Error: Cannot listen on port " + port + " : " + e);
System.exit(1);
}
while (true) // infinite loop - loops once for each client
{
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept(); //waits here (forever) until a client connects
System.out.println("Server has just accepted socket connection from a client");
GlobalVariables.sinterface.setServerStatus("Server has just accepted socket connection from a client");
} catch (IOException e) {
System.out.println("Accept failed: " + e);
GlobalVariables.sinterface.setServerStatus("Accept failed: " + e);
break;
}
// Create the Handle Connection object - our new thread object - only create it
ThreadedHandleConnection con = new ThreadedHandleConnection(clientSocket);
if (con == null) //If it failed send and error message
{
try {
ObjectOutputStream os = new ObjectOutputStream(clientSocket.getOutputStream());
os.writeObject("error: Cannot open socket thread");
os.flush();
os.close();
} catch (Exception ex) //failed to even send an error message
{
System.out.println("Cannot send error back to client: " + ex);
GlobalVariables.sinterface.setServerStatus("Cannot send error back to client: " + ex);
}
} else {
con.start();
} // otherwise we have not failed to create the HandleConnection object
// start this thread now
}
try // do not get here at the moment
{
System.out.println("Closing server socket.");
GlobalVariables.sinterface.setServerStatus("Closing server socket.");
serverSocket.close();
} catch (IOException e) {
System.err.println("Could not close server socket. " + e.getMessage());
GlobalVariables.sinterface.setServerStatus("Could not close server socket. " + e.getMessage());
}
}
}
Connection Handler:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tcpServer_package;
import java.net.*;
import java.io.*;
import java.util.*;
import busimesslogic_package.Functions;
/**
*
* #author wsserver
*/
public class ThreadedHandleConnection extends Thread {
private Socket clientSocket; // Client socket object
private ObjectInputStream is; // Input stream
private ObjectOutputStream os; // Output stream
// The constructor for the connecton handler
public ThreadedHandleConnection(Socket clientSocket) {
this.clientSocket = clientSocket;
}
// The main thread execution method
public void run() {
try {
this.is = new ObjectInputStream(clientSocket.getInputStream());
this.os = new ObjectOutputStream(clientSocket.getOutputStream());
while (this.readCommand()) {
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Receive and process incoming command from client socket
private boolean readCommand() {
String wholeCommand = null;
try {
wholeCommand = (String) is.readObject();
} catch (Exception e) {
wholeCommand = null;
}
if (wholeCommand == null) {
this.closeSocket();
return false;
}
System.out.println("Received: "+wholeCommand);
//GET COMMAND PARAMETARS
String[] commParams = wholeCommand.split(";");
//GET COMMAND TYPE
int type = Integer.parseInt(commParams[0]);
//SELECT COMMAND PROCEDURE
Functions functions = new Functions();
String IPaddress = clientSocket.getRemoteSocketAddress().toString();
IPaddress = IPaddress.substring(IPaddress.indexOf("/")+1, IPaddress.indexOf(":"));
switch (type) {
case 1: {
String sendText = getTextToSend();
send(sendText);
break;
}
default:{
sendError("0;"+wholeCommand);
break;
}
}
System.gc();
return true;
}
// Send a message back through to the client socket as an Object
private void send(Object o) {
try {
System.out.println("Sending " + o);
this.os.writeObject(o);
this.os.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
// Send a pre-formatted error message to the client
public void sendError(String msg) {
this.send("error:" + msg); //remember a string IS-A object!
}
// Close the client socket
public void closeSocket() //close the socket connection
{
try {
this.os.close();
this.is.close();
this.clientSocket.close();
} catch (Exception ex) {
System.err.println(ex.toString());
}
}
}
Android Client Code:
package com.example.zpbitolaoperator;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import android.util.Log;
public class TCPClient{
//Comunication variables
private static Socket socket;
private static ObjectOutputStream os;
private static ObjectInputStream is;
//Server parametars
static String serverIP;
static int port;
//Communication status
static boolean connectionStatus = false;
public static boolean connectToServer() {
try // open a new socket to port: and create streams
{
serverIP = GlobalVariables.serverIP;
port = GlobalVariables.portNo;
socket = new Socket(serverIP, port);
os = new ObjectOutputStream(socket.getOutputStream());
is = new ObjectInputStream(socket.getInputStream());
Log.d("DEBUG", "Connected to Server");
connectionStatus = true;
return true;
} catch (Exception ex) {
Log.d("DEBUG", "Failed to Connect to Server " +ex.toString(), ex.getCause());
connectionStatus = false;
return false;
}
}
public static boolean closeConnection(String message){
try{
socket.close();
Log.d("DEBUG", "Closed connection to Server");
return true;
} catch (Exception ex){
Log.d("DEBUG", "Failed to close connection to Server " +ex.toString(), ex.getCause());
return false;
}
}
private static String sendMessage(String message) {
String returnString;
send(message);
returnString = (String) receive();
if (returnString != null) {
Log.d("DEBUG", "Server returned: " + returnString);
}else{
return returnString = "ERROR";
}
return returnString;
}
// method to send a generic object.
private static void send(Object o) {
try {
Log.d("DEBUG", "Sending: " + o);
os.writeObject(o);
os.flush();
} catch (Exception ex) {
Log.d("DEBUG", "Sending to server " +ex.toString(), ex.getCause());
}
}
// method to receive a generic object.
private static Object receive() {
Object o = null;
try {
o = is.readObject();
} catch (Exception ex) {
Log.d("DEBUG", "Receive from server " +ex.toString(), ex.getCause());
}
return o;
}
/**
* Isprakja poraka do server
* #param message
* #return ili ERROR ili poraka
*/
public synchronized static String sendToServer(String message) {
String rez = "";
try {
rez = sendMessage(message);
} catch (Exception ex) {
Log.d("DEBUG", "Send to server " +ex.toString(), ex.getCause());
}
return rez;
}
public static boolean getCommunicationStatus(){
return connectionStatus;
}
}
I am sending String data to my server (comand;param1;param2....), the server proces that data and returns some data do the android application. The android application is the TCP Client and the java application is the server. For every connection the server creates thread (infinite) that handles that connection. The problem is that my server cant send something without the client sending the request first. The ObjectInputStream readObject() blocks the thread until the client send some data. I want to use the same socket to send in the other direction (java -> android and the android application send some data back) .I know that this can be done by opening another socket where the Android will be the server and the java application will be the client. Is this posible and how?
If you want to be able to concurrently receive data from a client and send data to the client then you'll have to either use two threads per client (one to receive and one to send) or use non-blocking IO.

IOException after thousands of socket creation calls

Why IOException after thousands of socket creation calls?
I did a simple Server code (Java) which accepts connections then creates a thread reads the socket and sends back another character to the Client
The Client code starts to do a cycling (long enough to reproduce the issue) and in each cycle creates 50 threads in each thread creating a client socket to server machine and sends a character then reads from socket the character that the Server sends back.
Then both the Client and the Server closes the socket.
After a while I notice that on Client side I get exception in client socket creation.
Are there some limitations which I should take in consideration to work this properly or this should work in an infinite loop?
I'm thinking here to situations that maybe after a long enough cycling time the client side tries to bind the new socket to a port on client machine which is still binded to a socket which is in CLOSED state but that time period which needs to be elapsed to be freed by kernel not passed yet. (sorry don't know official name of this time period)
The client and server machines are two Linux systems in VMware.
Sounds like maybe your connection was dropped.
You forgot rule #1 in the Fallacies of Distributed Computing: The network is always reliable.
Have you set the setReuseAddress parameter to true on your ServerSocket? If not, you have to wait a quite long time before the kernel release network resources.
Thank you !
Actually this is my Server side code
public class TestServer {
public void createThread() {
System.out.println("createThread");
ServerThread servThread = new ServerThread();
servThread.start();
}
public static final void main(String[] args) {
ServerSocket server = null;
try {
System.out.println("Started");
server = new ServerSocket(12345);
}
catch(IOException ex) {
System.out.println("Server: Exception at socket creation: " + ex.getMessage());
}
try {
while(true) {
Socket clientSock = server.accept();
System.out.println("Connection Accepted: server: "+clientSock.getLocalPort()+", Client: "+clientSock.getPort());
ServerThread servThread = new ServerThread(clientSock);
servThread.start();
}
}
catch(IOException ex) {
System.out.println("Server: Exception at socket accept: " + ex.getMessage());
}
}
}
class ServerThread extends Thread {
private Socket sock;
public ServerThread() {}
public ServerThread(Socket sock) {
this.sock = sock;
}
public void run() {
InputStream is = null;
OutputStream os = null;
try {
is = sock.getInputStream();
os = sock.getOutputStream();
}
catch(IOException ex) {}
try {
int b = is.read();
System.out.println("server: received = " + (char)b);
}
catch(IOException ex) {
System.out.println("Server: IOException at read = " + ex.getMessage());
}
try {
os.write('R');
os.flush();
}
catch(IOException ex) {
System.out.println("Server: IOException at write = " + ex.getMessage());
}
try {
sock.close();
}
catch(IOException ex) {
System.out.println("Server: IOException at close = " + ex.getMessage());
}
}
}
and this is the Client part:
public class TestClient {
public static void main(String[] args) {
if (args.length != 4) {
System.out.println("Usage: java TestClient <ServerIP> <nbThreads> <cycle> <delay>");
System.exit(1);
}
String host = args[0];
int nbThreads = Integer.parseInt(args[1]);
int cycle = Integer.parseInt(args[2]);
int delay = Integer.parseInt(args[3]);
for (int i = 0; i<cycle; i++) {
for (int j = 0; j<nbThreads; j++) {
ClientThread clThread = new ClientThread(host);
clThread.start();
}
/* try {
Thread.sleep(delay);
}
catch (Exception ex) {} */
}
}
}
class ClientThread extends Thread {
private String host;
public ClientThread(String host) {
this.host = host;
}
public void run(){
for (int i=0; i<3; i++) {
Socket clientSock = null;
try {
clientSock = new Socket(host, 12345);
}
catch(IOException ex) {
System.out.println("Client: IOException at socket creation = " + ex.getMessage());
}
OutputStream os = null;
InputStream is = null;
try {
os = clientSock.getOutputStream();
is = clientSock.getInputStream();
}
catch (IOException ex) { }
try {
os.write('B');
os.flush();
}
catch (IOException ex) {
System.out.println("Client: IOException at write = " + ex.getMessage());
}
try {
int reply = is.read();
System.out.println("Client: reply = " + (char)reply);
}
catch(IOException ex) {
System.out.println("Client: IOException at read = " + ex.getMessage());
}
try {
clientSock.close();
}
catch(IOException ex) {
System.out.println("Client: IOException at close = " + ex.getMessage());
}
}
}
}
I'm testing with 60 threads and 1000 cycle and no delay.
I was wrong in my first question, the exception comes from the is.read() call after a while and it is 'Connection reset' exception.
I did this sample code to simulate the problem I'm getting in my application code where I'm getting the exception during the client socket creation ... but it seems I need to find further what is the difference netween this and my application code.
However I think would help me also to understand why after a while I'm getting the 'Connection reset' exception on the client side after a while.
Is that possible that on the server side once os.write('R') happened the sock.close() happens so fast that on the client side the is.read() call hasn't reached yet. Sound strange :)
Also not sure on which socket I should use the setReuseAddress function. Isn't on the client side, because there I'm creating again and again the sockets... although now I'm not getting the exception at client socket creation.
Thanks !

Server-Client communication problem

i'm working with an example of client-server programm on Java. I faced such a problem:
I start the server with 8080 port and a localhost, than I start a client and make a request. As soon as the request done both programms close theri sockets, so i can't repeat my actions. How can i use the same client and the same server to make more than one request?
public class Network extends Thread
{
MasterEdit ME = new MasterEdit();
private Socket _socket;
InputStream is; //Data streams
OutputStream os;
/**
* Network class constructor
*/
public Network(int port, int backlog, InetAddress address)
{
//We create an object of SocketFactory
SocketFactory sf = new SocketFactory();
//Save server socket
ServerSocket ss = null;
try
{
if(address == null) //If there is no host
{
if(backlog <= 0) //If backlog is not given we create it with port
{ ss = sf.createServerSocket(port);
System.out.println("Success");
}
else
ss = sf.createServerSocket(port, backlog); //If backlog is given we just create it
}
else
ss = sf.createServerSocket(port, backlog, address); //If everything is given we create it using data
}
catch(Exception e)
{
//Exception with creation of socket
System.err.println("Failed open server socket");
System.exit(1); //Stop program and send 1 as a exception-code
}
while(true) //Listening to the socket
{
try
{
StartThread(ss.accept()); //If client has connected we send him to the daemon
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* Start daemon-tool when client has connected
*/
private void StartThread(Socket ss)
{
_socket = ss; //initializing of global variable
setDaemon(true); //anounce that new potok is daemon
setPriority(NORM_PRIORITY); //set the priority
start(); //Start it
}
#Override
public void run()
{
byte buffer[] = new byte[64*1024]; //buffer in 64 kb
try
{
is = _socket.getInputStream();
os = _socket.getOutputStream(); //Initializing the output stream to a client
String toClient = SearchRequest(new String(buffer, 0, is.read(buffer)));
os.write(toClient.getBytes()); //Sending an answer
}
catch(Exception e)
{
e.printStackTrace();
}
}
private String SearchRequest(String request)
{
String info = ""; //Initializing of a variable
if(request.equalsIgnoreCase("info")) //Check the request
{
//Adding data
info += "Virtual Machine Information (JVM)n";
info += "JVM Name: " + System.getProperty("java.vm.name")+"n";
info += "JVM installation directory: " + System.getProperty("java.home")+"n";
info += "JVM version: " + System.getProperty("java.vm.version")+"n";
info += "JVM Vendor: " + System.getProperty("java.vm.vendor")+"n";
info += "JVM Info: " + System.getProperty("java.vm.info")+"n";
return info; //Give the answer
}
if(request.charAt(0)=='0') {
StringTokenizer rm = new StringTokenizer(request, " \t\n\r,:");
rm.nextToken();
ME.MasterDell(Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()));
return "Successfully deleted";
}
if(request.charAt(0)=='1'){
StringTokenizer temp = new StringTokenizer(request, " \t\n\r,:");
temp.nextToken();
ME.MasterAdd(Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), temp.nextToken());
return "Successfully added";
}
this.ClostIt();
return "Bad request"; //bad request
}
public void ClostIt() {
try {
is.close();
os.close();
_socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It's server part. It usess SocketFactory class but mainly it just creates a socket in the begining. In main programm i call new Network(PORT, BACKLOG, InetAddress.getByName(host));
I am guessing in your server program you don't have a loop but rather something like this:
public static void main( String args[] ) {
ServerSocket server = new ServerSocket(...);
Socket con = server.accept();
//process the client connection ...
//done, exit!
}
rather than
public static void main( String args[] ) {
ServerSocket server = new ServerSocket(...);
Socket con = null;
while( condition /* e.g. shutdown server message received */ ) {
con = server.accept();
//process the client connection ...
//then keep waiting for the next request
}
//done, exit!
}
Bear in mind the above sample only processes one client at a time! you will need to step into multi-threading for processing simultaneous clients.
This is a good starter for a multi threaded server
http://www.kieser.net/linux/java_server.html
Mark

Categories