Solved

Java Sockets --- Server and Client

Posted on 2009-04-05
11
277 Views
Last Modified: 2013-11-23
Hi I'm working on this program where I need to send a DataPacket object back and forth from server to client and viceversa.   Can you guys check my code, I dont think I'm doing it correctly.  The server cannot listen to the port and the client seems not to be doing anything.

P.S.  They must work on different computers on the same network.  So I'm guessing I would need a method to set up the ip address of the server?
import java.io.*;
 
import java.net.*;
 
 
 
public class Client {
 
	
 
    Socket echoSocket = null;
 
    ObjectOutputStream out = null;
 
    ObjectInputStream in = null;
 
    String packet = null;
 
    
 
    public Client(){
 
        try {
 
            echoSocket = new Socket("127.0.0.1", 10007);
 
            out = new ObjectOutputStream(echoSocket.getOutputStream());
 
            in = new ObjectInputStream(echoSocket.getInputStream());
 
            System.out.println("Client started successfuly");
 
 
 
        } catch (UnknownHostException e) {
 
            System.err.println("Don't know about host: ");
 
            System.exit(1);
 
        } catch (IOException e) {
 
            System.err.println("Couldn't get I/O for the connection to the server.");
 
            System.exit(1);
 
        }
 
    }
 
 
 
    public void getData(){
 
        try {
 
            packet = (String)in.readObject();
 
           }
 
       catch (Exception ex)
 
           {
 
            System.out.println (ex.getMessage());
 
           }
 
 
 
    }
 
    
 
 
 
    public void sendData(String dp){
 
    	try {
 
			out.writeObject(dp);
 
		} catch (IOException e) {
 
			e.printStackTrace();
 
		}
 
        try {
 
			out.flush();
 
		} catch (IOException e) {
 
			e.printStackTrace();
 
		}
 
    }
 
    
 
    
 
 
 
}
 
 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 
 
 
import java.net.*; 
 
import java.io.*; 
 
 
 
public class Server 
 
{ 
 
	ServerSocket serverSocket = null;
 
	Socket clientSocket = null;
 
	ObjectOutputStream out = null;
 
	ObjectInputStream in = null;
 
	int port;
 
	boolean isConnected = false;
 
 
 
	String packet = null;
 
	
 
	public Server(){
 
		try{
 
			serverSocket = new ServerSocket(10007);
 
			isConnected = true;
 
			System.out.println("server started successfully");
 
			
 
		}
 
		catch (IOException e){
 
			System.err.print("Could not listen on port: 10007");
 
			System.exit(1);
 
		}
 
		try{
 
			System.out.println("Waiting for Client");
 
			clientSocket = serverSocket.accept();
 
		}
 
		catch (IOException e){
 
			System.err.println("Accept failed.");
 
			System.exit(1);
 
	}
 
		try {
 
			out = new ObjectOutputStream(clientSocket.getOutputStream());
 
			System.out.println("output stream created successfully");
 
		} catch (IOException e) {
 
				e.printStackTrace();
 
		}
 
		try {
 
			in = new ObjectInputStream(clientSocket.getInputStream());
 
			System.out.println("input stream created successfully");
 
		} catch (IOException e) {
 
				e.printStackTrace();
 
		}
 
	}
 
	
 
	public void getData(){
 
	    try {
 
	         packet = (String)in.readObject();
 
	        }
 
	    catch (Exception ex)
 
	        {
 
	         System.out.println (ex.getMessage());
 
	        }
 
	}
 
	
 
	public void sendData(String dp){
 
	    try {
 
			out.writeObject(dp);
 
		} catch (IOException e) {
 
			e.printStackTrace();
 
		} 
 
	    try {
 
			out.flush();
 
		} catch (IOException e) {
 
			e.printStackTrace();
 
		}
 
	}
 
	
 
	public void closeConnection() throws IOException{
 
		out.close(); 
 
		in.close(); 
 
		clientSocket.close(); 
 
		serverSocket.close(); 
 
   } 
 
} 
 
 
 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 
public class ServerApp{
 
 
	public static void main(String [] args){
 
		Server server = new Server();
}
}
 
 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 
public class ClientApp{
 
 
	public static void main(String [] args){
 
		Client client = new Client();
}
}

Open in new window

0
Comment
Question by:ubuntuguy
  • 6
  • 4
11 Comments
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 24072942
Immediately after this line:

  serverSocket = new ServerSocket(10007)

add this line:

  clientSocket = serverSocket.accept();
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 24072953
The constructor of ServerSocket merely produces an instance; in order to actually listen to the port for incoming connections, you call ServerSocket#accept(), which will listen for the connections and then return a Socket instance for that connection.
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 24072982
Tip: If you need to support more than one client simultaneously, then you'll do this by creating a while-loop to keep checking for new incoming connections, and when one is received, pass it to a new thread to be dealt with.
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 12

Expert Comment

by:basav_com
ID: 24073156
Check these examples for more understanding:
http://www.ibiblio.org/java/books/jnp/javanetexamples/index.html

post the error if you are facing any problems with your current code.
0
 
LVL 1

Author Comment

by:ubuntuguy
ID: 24073374
OK let's take my Server example below:  I can create a server object and I want to send an object i simply call server.sendData();

but I need to be listening for incoming objects... do I need a loop for that calling the getData() method? Or does the ServerSocket handles this on its own?



package proj4;
 
import java.net.*; 
import java.io.*; 
 
public class Server 
{ 
	ServerSocket serverSocket = null;
	Socket clientSocket = null;
	ObjectOutputStream out = null;
	ObjectInputStream in = null;
	int port;
	boolean isConnected = false;
 
	DataPacket packet = null;
	
	public Server(){
		try{
			serverSocket = new ServerSocket(30000);
			serverSocket.setSoTimeout(1000*120); //2 minutes timeout time
			isConnected = true;
			System.out.println("server started successfully");
			
		}
		catch (IOException e){
			System.err.print("Could not listen on port: 3000");
			System.exit(1);
		}
		try{
			System.out.println("Waiting for Client");
			clientSocket = serverSocket.accept();
		}
		catch (IOException e){
			System.err.println("Accept failed.");
			System.exit(1);
		}
		try {
			out = new ObjectOutputStream(clientSocket.getOutputStream());
			System.out.println("output stream created successfully");
		} catch (IOException e) {
				e.printStackTrace();
		}
		try {
			in = new ObjectInputStream(clientSocket.getInputStream());
			System.out.println("input stream created successfully");
		} catch (IOException e) {
				e.printStackTrace();
		}
	}
	
	public void getData(){
	    try {
	         packet = (DataPacket)in.readObject();
	        }
	    catch (Exception ex)
	        {
	         System.out.println (ex.getMessage());
	        }
	}
	
	public void sendData(DataPacket dp){
	    try {
			out.writeObject(dp);
		} catch (IOException e) {
			e.printStackTrace();
		} 
	    try {
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void closeConnection() throws IOException{
		out.close(); 
		in.close(); 
		clientSocket.close(); 
		serverSocket.close(); 
   } 
} 

Open in new window

0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 24073507
Yes, you need to loop. I suggest creating a separate thread for this.

while(keep_listening)
{
    DataPacket dp=getData();
    // do something with it
}
0
 
LVL 1

Author Comment

by:ubuntuguy
ID: 24073738
OK, I fixed my code.  Can you look at it and tell me if it will work on the network? Or will it only work on the local machine?

package proj4;
 
import java.net.*; 
import java.io.*; 
 
public class Server implements Runnable 
{ 
	ServerSocket serverSocket = null;
	Socket clientSocket = null;
	ObjectOutputStream out = null;
	ObjectInputStream in = null;
	int port;
	static int defaultPort=30000;
	boolean isConnected = false;
	Thread thread;
 
	DataPacket packet = null;
	
	public Server(int _port){
		try{
			serverSocket = new ServerSocket(_port);
			serverSocket.setSoTimeout(1000*120);  //2 minutes time out 
			isConnected = true;
			System.out.println("server started successfully");
			thread = new Thread(this);
			thread.setDaemon(true);
			//thread.run();
			
		}
		catch (IOException e){
			System.err.print("Could not listen on port: " + port);
			System.exit(1);
		}
		try{
			System.out.println("Waiting for Client");
			clientSocket = serverSocket.accept();
			System.out.println("Client Connected");
			thread.run();
		}
		catch (IOException e){
			System.err.println("Accept failed.");
			System.exit(1);
		}
		try {
			out = new ObjectOutputStream(clientSocket.getOutputStream());
			System.out.println("output stream created successfully");
		} catch (IOException e) {
				e.printStackTrace();
		}
		try {
			in = new ObjectInputStream(clientSocket.getInputStream());
			System.out.println("input stream created successfully");
		} catch (IOException e) {
				e.printStackTrace();
		}
	}
	
	public Server(){
		this(defaultPort); //server listens to port 30000 as default
	}
	
	
	public void run()
	{
		System.out.println("Thread running, listening for clients");//debugging purposes
		while(isConnected){
			try{
				packet = this.getData();
				Thread.sleep(0);
			}
			catch(InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	} 
	
	public DataPacket getData(){
	    try {
	    	 packet = (DataPacket)in.readObject();
	        }
	    catch (Exception ex)
	        {
	         System.out.println (ex.getMessage());
	        }
	    return packet;
	}
	
	public void sendData(DataPacket dp){
	    try {
			out.writeObject(dp);
		} catch (IOException e) {
			e.printStackTrace();
		} 
	    try {
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void closeConnection() throws IOException{
		out.close(); 
		in.close(); 
		clientSocket.close(); 
		serverSocket.close(); 
   }
 
 
} 

Open in new window

0
 
LVL 1

Author Comment

by:ubuntuguy
ID: 24074265
OK I got both the server and client working... one last thing.

When I add a new Server or client to my GUI application it stops working.  How do I go about fixing this?
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 24075956
Well show us all of your code (including your GUI stuff).
If by 'stops working' you mean that the GUI freezes, then I would guess that you're not handling new connections in a separate thread to the GUI.
0
 
LVL 25

Accepted Solution

by:
InteractiveMind earned 500 total points
ID: 24075995
I've just spotted a problem with your code; this line:

  isConnected = true;

should appear after this line:

  clientSocket = serverSocket.accept();

furthermore, you're not starting the thread correctly. This line:

  thread.run();

merely calls the method, it does not make it run in a separate thread! Instead, call:

  thread.start();

This will initiate the run() method, but in its own thread.


Another thing, although not highly important: you've placed essentially all operations into their own try-catch block. This is bad coding practice, and unnecessary in your case, because if any of those lines fail then your entire program should fail, whereas your existing code will just output the error and then continue running (and then inevitably run into more errors).


> Can you look at it and tell me if it will work on the network? Or will it only work on the local machine?

If it works on the local machine, then it will work on the network (as long as there are no firewalls blocking it).

0
 
LVL 1

Author Closing Comment

by:ubuntuguy
ID: 31566820
thanks for your help
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Claiming a Domain Name 7 35
winscp 000webhost.com 6 50
eclipse console opening separately 2 19
Lightweight Networking 9 37
#Citrix #Citrix Netscaler #HTTP Compression #Load Balance
Join Greg Farro and Ethan Banks from Packet Pushers (http://packetpushers.net/podcast/podcasts/pq-show-93-smart-network-monitoring-paessler-sponsored/) and Greg Ross from Paessler (https://www.paessler.com/prtg) for a discussion about smart network …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question