Advertisement

Can I Make This Code Faster Without Over Complicating It ?

Started by October 14, 2014 08:51 PM
6 comments, last by rip-off 10 years, 1 month ago

I have been working on test code for a client/server to implement into an existing project.

My question is: could I improve the code to make it run faster, WITHOUT overcomplicated things ?

Once I implement this into my existing code, it will probably have to handle between 10 to 20 updates per second ( several different object types possible. )

***

MAIN

***


public class Main {

	public static void main (String[] args){
		TestObj to = new TestObj();
		Client client = new Client();
		Server server = new Server();
		Thread t = new Thread(server,"");
		t.start();
		
		to.set("Moo");
		client.out(to);
		to.set("Baa");
		client.out(to);
		to.set("Quack");
		client.out(to);
	}
}

***

TestObj ( only used for this code test )

***


public class TestObj implements Serializable {
	String s;
	
	public void set(String str){
		s = str;
	}

	public void say(){
		System.out.println("You said: " + s);
	}
}

***

Client

***


public class Client {

	Socket socket;
	ObjectInputStream input;
	ObjectOutputStream output;

	
	public void out(Object obj){
		try{
			socket = new Socket ("127.0.0.1",1660);
			output = new ObjectOutputStream (socket.getOutputStream());
			output.writeObject(obj);
		}
		catch(Exception e){
			System.out.println("Client Crash\n" + e);
		}
	}
}

***

Server

***


public class Server implements Runnable {
	ServerSocket ssocket;
	Socket socket;
	ObjectInputStream input;
	Object dump;
	TestObj to;
	
	@Override
	public void run() {
		try{
			ssocket = new ServerSocket(1660);
			
			while (true){
			socket = ssocket.accept();
			input = new ObjectInputStream(socket.getInputStream());
			dump = input.readObject() ;
			socket.close();
			// if (dump instanceof TestObject){}
			to = (TestObj) dump;
			to.say();
			} 
			
		} 
		catch (Exception e){
			System.out.println("Server Crash\n" + e);
		}
		
	}
}

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

Don't create a new socket every time you do an out, rather create the socket and connect to the server once (in the constructor perhaps?), then issue all the commands after that without having to close and re-open the connection each time. Close the socket when the client is done.

Similar with the server, have it not only listen for new connections, but also listen for data from existing open connections.

That alone should improve the efficiency.

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

Advertisement

I'm getting null pointer errors whenever I move bits of code into the class constructor in both server and client ...

Edit - Multi threading the connections is becoming a nightmare - as of right now a new thread is created every time I connect ...

The way it is written works, but creates a memory leak at the same time angry.png

*** Server ***


public class Server implements Runnable {
	ServerSocket ssocket;
	Socket socket ;
	ObjectInputStream input;
	Object dump;
	TestObj to;
	
	@Override
	public void run() {
		try{
			ssocket = new ServerSocket(1660);

			while (true){
			socket = ssocket.accept();
			Connect connect = new Connect(socket);
			Thread t = new Thread(connect,"");
			t.start();
			
			} 
				} 
		catch (Exception e){
			System.out.println("Server Crash\n" + e);
		}
		
	}
}

*** Connect ***


public class Connect implements Runnable {
	ServerSocket ssocket;
	Socket socket ;
	ObjectInputStream input;
	Object dump;
	TestObj to;

	
	public Connect(Socket so){
		socket = so;
	}
	
	
	@Override
	public void run() {
		try{
			while(true){
			input = new ObjectInputStream(socket.getInputStream());
			dump = input.readObject() ;
			//socket.close();
			to = (TestObj) dump;
			to.say();
			}
		}
		catch (Exception e){
			System.out.println("Connect Crashed\n" + e);
		}
	}
	

}

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

The way it is written works, but creates a memory leak at the same time
Then don't do a while(true) inside Connect.

Implement a timeout. Sleep the thread, see if there is new data, sleep a bit more, and if new data doesn't enters in X amount of time, close the connection. run() method ends and Thread is GC'd.

Also, don't 'new' Threads willy nilly. Use executors. Fix the amount of threads you want to make to handle connections. Threads aren't cheap to make, nor cheap to maintain (10Mb per Thread instance IIRC).

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator

Shippou, you're not doing it right.

I'm not familiar with Java's socket implementation, but google "java socket select", as you want to perform a select (or Java equivalent) on the server socket (to accept incoming connections), as well as all the already connected sockets. That will wake (or timeout if you want) whenever there is a new connection or data to be read on an open socket. I wouldn't use a Thread for the server or the client for that matter.

For the client, why can't you, when you go to send data, check if it's connected, and, if not, do a connect (saving the socket), then just send data after that.

IMO, you should probably just find a good tutorial on Java client/server as it should cover all of this. Good luck and have fun.

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

Please give links to WORKING code that demonstrates how to keep a server - client connection open ... I have been working on the problems of my code for over 14 hours now - and I can not find anything more than - throw away examples, code that is written far worse than mine, and examples that do not actually keep a connection alive.

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

Advertisement

Please give links to WORKING code that demonstrates how to keep a server - client connection open ... I have been working on the problems of my code for over 14 hours now - and I can not find anything more than - throw away examples, code that is written far worse than mine, and examples that do not actually keep a connection alive.

I googled "java client server tutorial" and the first two links were Oracle documentation on Java sockets that appears to connect once then repeatedly send/receive data until an arbitrary disconnect message is received. The code also doesn't appear to be any worse than yours, but I guess that could be a matter of opinion.


Please give links to WORKING code that demonstrates how to keep a server - client connection open ... I have been working on the problems of my code for over 14 hours now - and I can not find anything more than - throw away examples, code that is written far worse than mine, and examples that do not actually keep a connection alive.

What have you tried searching for?

This topic is closed to new replies.

Advertisement