Solved

Java Sockets --- Server and Client

Posted on 2009-04-05
11
275 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
 
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Meet the world's only “Transparent Cloud™” from Superb Internet Corporation. Now, you can experience firsthand a cloud platform that consistently outperforms Amazon Web Services (AWS), IBM’s Softlayer, and Microsoft’s Azure when it comes to CPU and …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

760 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now