Overclock.net - Overclocking.net
     
 
Home Gallery Reviews Blogs Register Today's Posts Mark Forums Read Members List


Go Back   Overclock.net - Overclocking.net > Software, Programming and Coding > Coding and Programming > Application Programming

Reply
 
LinkBack Thread Tools
Old 05-27-09   #1 (permalink)
New to Overclock.net
 
adramalech707's Avatar
 
intel nvidia

Join Date: Feb 2008
Posts: 219

Rep: 5 adramalech707 Unknown
Unique Rep: 5
Folding Team Rank: 691
Trader Rating: 0
Default tcp/ip socket server in java

okay i need some help i have to main methods one is the server the other is the client i have finished coding them....it is a pretty simple procedure but i am thinking of it like i would if i did it in c....where i have two main methods and i run the server i then run the client.....and then until the client is up and sends something then the server will wait in limbo....and visa versa...once the server is up and the client is up and the client sent its okay status the server will send the request for a number and will then wait for a return....atleast this is the plan

it will then repeat until i send bye...

here is my server code so far:

Code:
package server;

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

public class Server_Socket {
	//setup constants
	protected static final int PORT_NUM = 5000;
	protected static final int BACKLOG = 5;
	
	public static void main(String[] args) {
		//declare variables to null
		ServerSocket server = null;
		Socket incoming = null;
		BufferedReader in = null;
		PrintWriter out = null;
		boolean done = false;
		String newLine = null;
		int num = 0;
		
		//create a socket and binds it
		try{
			server = new ServerSocket(PORT_NUM, BACKLOG, InetAddress.getLocalHost() );
		}
		catch(Exception e){
			System.out.println("Incountered an error in creating the server socket: " + e);
		}
		
		//accept the client
		try{
			incoming = server.accept();
		}
		catch(Exception e){
			System.out.println("Incountered an error in accepting the client: " + e);
		}
		
		//send and receive data
		try{
		    in = new BufferedReader
		      (new InputStreamReader(incoming.getInputStream()));
		    out = new PrintWriter
		      (incoming.getOutputStream(), true /* autoFlush */);
		    Scanner scan = new Scanner(in);
		    
		    //wait till we get a ready status
		    while(newLine.compareTo("Ready") == 0){
		    	newLine.wait(100);
		    	newLine = in.readLine();
		    }
		    
		    //reset newLine
		    newLine = null;
		    
		    //send to client that it is ready to take the number...
		    while(!done){
		    	out.write("Please enter a number to be squared: ");
		    	
		    	//again wait till we get a return
		    	while(newLine == null){
		    		newLine.wait(100);
		    		newLine = in.readLine();
		    	}
		    	
		    	if(newLine != null){
		    		if(newLine.compareTo("Bye") != 0){
		    			num = scan.nextInt();
		    			num = num^2;
		    			out.write(num);
		    		}
		    		else{
		    			done = true;
		    		}
		    	}
		    	else{
		    		done = true;
		    	}
		    }
		}
		catch(Exception e){
			System.out.println("There was an error in receiving or sending data: " + e);
		}
		
		//we are done so close connections
		try{
			incoming.close();
		}
		catch(Exception e){
			System.out.println("Was unable to close, either the connections where cut or connection timed out " + e);
		}
	}
}
here is my client code:

Code:
package client;
import java.net.*;
import java.util.*;
import java.io.*;

public class Client_Socket {
	protected static final int PORT_NUM = 5000;
	protected static final String MACHINE = "localhost";

	public static void main(String[] args) {
		Socket The_Client = null;
		String line = null;
		int num = 0;
		//create a socket and connect
		try{
			The_Client = new Socket(MACHINE, PORT_NUM);
		}
		catch(Exception e){
			System.out.println("There was a " + e + " error in connecting to the server! Please try again.");
		}
		
		//Send and or receive data
		try{
		    BufferedReader in = new BufferedReader
		      (new InputStreamReader(The_Client.getInputStream()));
		    PrintWriter out = new PrintWriter
		      (The_Client.getOutputStream(), true /* autoFlush */);
		    Scanner scan = new Scanner(System.in);	
		    
		    //send it is ready to receive the query
		    out.write("Ready");
		    
		    //this is waiting for server to return the number then closes else will stay open
			while(num != 999){
				if(line == null){
					line.wait(100);
					line = in.readLine();
				}
			    else{
			    	if(line.length() > 3){
			    		System.out.println("This is the result: " + line);
			    	}
			    	else{//it asked to enter a number...
			    		System.out.println(line);
			    		num = scan.nextInt();
			    		if(num != 999){
			    			out.write(num);
			    		}
			    	}
			    }
			}
		}
		catch(Exception e){
			System.out.println("There was an error in sending or receiving data " + e);
		}
		
		//close the socket and output input stream
		try{
			The_Client.close();
		}
		catch(Exception e){
			System.out.println("There was an error in closing the server, " + e);
		}
	}
}

here is my output to console when i run server first then i run client right after i hit run server...

Code:
There was a java.net.ConnectException: Connection refused: connect error in connecting to the server! Please try again.
There was an error in sending or receiving data java.lang.NullPointerException
There was an error in closing the server, java.lang.NullPointerException
i am wondering what i should do???? i am just trying to learn this on java through eclipse ide....i know how to do it in c and it is more complex with having to run 5 different instances and running rcpgen etc....

this seems to be less complex but more of a hassle....

how do i run two main methods in two different classes at once in the same project...can i just make one main method to run both main methods???

or do i need to manually run each class???

**EDIT:
okay so i just ran the server and let it run and it just sat there and did nothing waiting till the client was ran...

so i take it the server so far is doing its job...i will put in alot of println's to have the ability to follow what happens...
__________________
x2 4600+ @2.6ghz

x2 6400+ @ 3.5ghz

Quote:
When you say "I wrote a program that crashed Windows", people just stare at you blankly and say "Hey, I got those with the system, *for free*"
-Linus Torvalds
Quote:
"How should I know if it works? That's what beta testers are for. I only coded it."
-Linus Torvalds
Quote:
Be warned that typing \fBkillall \fIname\fP may not have the desired effect on non-Linux systems, especially when done by a privileged user.
-killall man page

System: Intel build
CPU
i7 860 @ 2.8ghz
Motherboard
gigabyte p55-ud6
Memory
dominator gt CMG4GX3M2A1600C7
Graphics Card
bfg 9600gt oc2
Hard Drive
wd caviar 500gb
Power Supply
750watt toughpower
Case
antec 900
CPU cooling
coolermaster hyper tx3
GPU cooling
stock
OS
windows 7/ gentoo 64bit
Monitor
samsung 2243swx

Last edited by adramalech707 : 05-27-09 at 11:39 PM
adramalech707 is offline I fold for Overclock.net   Reply With Quote
Old 05-29-09   #2 (permalink)
New to Overclock.net
 
adramalech707's Avatar
 
intel nvidia

Join Date: Feb 2008
Posts: 219

Rep: 5 adramalech707 Unknown
Unique Rep: 5
Folding Team Rank: 691
Trader Rating: 0
Default

okay so i seem to get pretty far....i atleast know that i create the socket on client and server...and that the server does accept the client...

the issue i am at right now...is writing to the out stream and then checking the in stream on the other side to see if out stream wrote anything so i can take the number and square it....so here is the code right now....

now i know i shouldn't be using the sleep method as how i have it setup it will just lag out the cpu..but since the variable i am using can be null the first time through i cannot tell wait on a null variable without getting null pointer exception...

another thing is if i am actually doing the right thing with the i/o stuff???

i did find a way to have the client in one workspace and the server in another and run to instances of eclipse ide actually allowed me to see how far on each side they got before crashing....the server was good but i cannot tell if it actually executed the out.write line where it asks for a number.... because when i go to the client while debugging after a couple loops the in stream is still null.....

the client
Code:
package client;
import java.net.*;
import java.util.*;
import java.io.*;

public class Client_Socket {
	protected static final int PORT_NUM = 5000;
	
	private static void sleep(int num){
		int i = 0;
		while(i <= num){
			i++;
		}
	}
	
	public static void main(String[] args) {
		Socket The_Client = null;
		String line = null;
		int num = 0;
		
		//create a socket and connect
		try{
			The_Client = new Socket(InetAddress.getLocalHost(), PORT_NUM);
			System.out.println("Client is connected to the server!");
		}
		catch(Exception e){
			System.out.println("There was a " + e + " error in connecting to the server! Please try again.");
		}
		
		//Send and or receive data
		try{
		    BufferedReader in = new BufferedReader
		      (new InputStreamReader(The_Client.getInputStream()));
		    PrintWriter out = new PrintWriter
		      (The_Client.getOutputStream(), true /* autoFlush */);
		    Scanner scan = new Scanner(System.in);
		
		    //this is waiting for server to return the number then closes else will stay open
			while(num != 999){
				if(line == null){
					sleep(100);
					line = in.readLine();
				}
			    else{
			    	if(line.length() > 3){
			    		System.out.println("This is the result: " + line);
			    	}
			    	else{//it asked to enter a number...
			    		System.out.println(line);
			    		num = scan.nextInt();
			    		if(num != 999){
			    			out.write(num);
			    		}
			    	}
			    }
			}
		}
		catch(Exception e){
			System.out.println("There was an error in sending or receiving data " + e);
		}
		
		//close the socket and output input stream
		try{
			The_Client.close();
		}
		catch(Exception e){
			System.out.println("There was an error in closing the server, " + e);
		}
	}
}
the server
Code:
package server;
import java.net.*;
import java.util.*;
import java.io.*;

public class Server_Socket {
	//setup constants
	protected static final int PORT_NUM = 5000;
	protected static final int BACKLOG = 5;
	
	private static void sleep(int num){
		int i = 0;
		while(i <= num){
			i++;
		}
	}
	
	public static void main(String[] args) {
		//declare variables to null
		ServerSocket server = null;
		Socket incoming = null;
		BufferedReader in = null;
		PrintWriter out = null;
		boolean done = false;
		String newLine = null;
		int num = 0;
		
		//create a socket and binds it
		try{
			server = new ServerSocket(PORT_NUM, BACKLOG, InetAddress.getLocalHost() );
			System.out.println("Server has been connected ");
		}
		catch(Exception e){
			System.out.println("Incountered an error in creating the server socket: " + e);
		}
		
		//accept the client
		try{
			incoming = server.accept();
			System.out.println("The server accepts the client!");
		}
		catch(Exception e){
			System.out.println("Incountered an error in accepting the client: " + e);
		}
		
		//send and receive data
		try{
		    in = new BufferedReader
		      (new InputStreamReader(incoming.getInputStream()));
		    out = new PrintWriter
		      (incoming.getOutputStream(), true /* autoFlush */);
		    
		    //send to client that it is ready to take the number...
		    while(!done){
		    	out.write("Please enter a number to be squared, or 999 to quit: ");
		    	
		    	//again keep checking till we get a return
		    	while(newLine == null){
		    		sleep(100);
		    		newLine = in.readLine();
		    	}
		    	if(newLine.compareTo("Bye") != 0){
		    		try{
		    			num =  Integer.parseInt(newLine.trim());
		    			num = num^2;
		    			out.write(num);
		    		}
		    		catch(NumberFormatException nfe){
		    	         System.out.println("NumberFormatException: " + nfe.getMessage());
		    	    }
		    	}
		    	else{
		    		done = true;
		    	}		    	
		    }
		}
		catch(Exception e){
			System.out.println("There was an error in receiving or sending data: " + e);
		}
		
		//we are done so close connections
		try{
			incoming.close();
		}
		catch(Exception e){
			System.out.println("Was unable to close, either the connections where cut or connection timed out " + e);
		}
	}
}
__________________
x2 4600+ @2.6ghz

x2 6400+ @ 3.5ghz

Quote:
When you say "I wrote a program that crashed Windows", people just stare at you blankly and say "Hey, I got those with the system, *for free*"
-Linus Torvalds
Quote:
"How should I know if it works? That's what beta testers are for. I only coded it."
-Linus Torvalds
Quote:
Be warned that typing \fBkillall \fIname\fP may not have the desired effect on non-Linux systems, especially when done by a privileged user.
-killall man page

System: Intel build
CPU
i7 860 @ 2.8ghz
Motherboard
gigabyte p55-ud6
Memory
dominator gt CMG4GX3M2A1600C7
Graphics Card
bfg 9600gt oc2
Hard Drive
wd caviar 500gb
Power Supply
750watt toughpower
Case
antec 900
CPU cooling
coolermaster hyper tx3
GPU cooling
stock
OS
windows 7/ gentoo 64bit
Monitor
samsung 2243swx
adramalech707 is offline I fold for Overclock.net   Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools



All times are GMT -5. The time now is 12:39 PM.


Overclock.net is a Carbon Neutral Site Creative Commons License

Terms of Service / Forum Rules | Privacy Policy | DMCA Info | Advertising | Become an Official Vendor
Copyright © 2009 Shogun Interactive Development. Most rights reserved.
Page generated in 0.11624 seconds with 8 queries