Solved

Java Sockets --- Server and Client

Posted on 2009-04-05
11
281 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
Don't Cry: How Liquid Web is Ensuring Security

WannaCry is just the start. Read how Liquid Web is protecting itself and its customers against new threats.

 
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

Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

Question has a verified solution.

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

Short answer to this question: there is no effective WiFi manager in iOS devices as seen in Windows WiFi or Macbook OSx WiFi management, but this article will try and provide some amicable solutions to better suite your needs.
WARNING:   If you follow the instructions here, you will wipe out your VTP and VLAN configurations.  Make sure you have backed up your switch!!! I recently had some issues with a few low-end Cisco routers (RV325) and I opened a case with Cisco TA…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
If you're a developer or IT admin, you’re probably tasked with managing multiple websites, servers, applications, and levels of security on a daily basis. While this can be extremely time consuming, it can also be frustrating when systems aren't wor…

707 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