?
Solved

Java Sockets --- Server and Client

Posted on 2009-04-05
11
Medium Priority
?
283 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

 
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 1500 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

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

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

This article will inform Clients about common and important expectations from the freelancers (Experts) who are looking at your Gig.
This article is a collection of issues that people face from time to time and possible solutions to those issues. I hope you enjoy reading it.
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Suggested Courses
Course of the Month14 days, 4 hours left to enroll

801 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