Results 1 to 7 of 7
  1. #1
    xenoepist is offline Xenoepist
    Join Date
    Jan 2012
    Location
    Brownsville, Tx
    Posts
    5
    Rep Power
    0

    Question TCP Two-Client-Server/Client Program not doing what I expected

    I am trying to create a 2-Client 1-Server program that communicates both clients between each other, so that if one client disconnects, the communication can be re-established without finding the new IP. If you need something like this, hopefully you can use this code. Latter I am planning to use this code to communicate two phones

    My code is mostly working, but when I disconnect one of the clients I get unexpected results, also, one of the clients is not receiving the correct data, which is weird since both clients have the same code. I've been working on this for days and it's getting me frustrated, please help!

    Sorry, guys I have to post the whole code for this one. Both Client and Server. Also, please note that in order for this code to work, you will need to change the ip address to your own machine and there needs to be two clients working or set a loopback at the server by adjusting the ports. Also, the reason I made a loop that sends data is because I need it to be constant data exchange between each client, for GPS updates and stuff like that (not yet included in the code). Hopefully I put enough comments on the code to make it more understandable, but if not, please let me know. Thanks!


    Java Code:
    //******SERVER*********
    //The reason I used one port to send and other to receive instead of one that does both, is because it will cause an
    //Address already in use exception. That's because the socket connected to that port will be accepted twice (once by
    // each thread).
    public class Server{
    	//You only need to select Port1Send, automatically Port1Receive will be equal to Port1S +100
    	//Port2S = Port1S + 1000 and Port2R = Port2S + 100. That is just so if they ports don't close,
    	//you only need to change one parameter instad of 4
    	//Example. if Port1S = 1000, Port1R = 1100
    	//			  Port2S = 2000, Port2R = 2100
    	private static final int Port1S = 1009,
    							 Port1R = Port1S+100; 
    	private static final int Port2S = Port1S+1000, 
    							 Port2R = Port2S+100; 
    	
    	public static void main(String[] args) {
    		System.out.println("Server Services Started");
    		//To do a loopback, try Resender(Port1R, Port1S) or Resender(Port2R, Port2S)
    		Thread oneToTwo = new Thread(new Resender(Port1R, Port2S, "Server 1"));//Receives data from Client1 and sends it to Client2
    		Thread twoToOne = new Thread(new Resender(Port2R, Port1S, "Server 2"));//Receives data from Client2 and sends it to Client1
    		twoToOne.start();
    		oneToTwo.start();
    		
    
    	}
    
    }
    Java Code:
    ///////Server Thread
    
    import java.io.*;
    import java.net.*;
    
    
    public class Resender implements Runnable {
    	private int sendPort, receivePort;	
    	ServerSocket sendServerSocket, receiveServerSocket;
    	String name = "Server";
    	
    	//Constructors set the Port from where they receive the data and 
    	//the port to where they send the data received. Also set the name. 
    	//If the name is not set, the default is Server
    	public Resender(int sendPort, int receivePort, String name){
    		this.sendPort = sendPort;
    		this.receivePort = receivePort;
    		this.name = name;
    	}
    	public Resender(int sendPort, int receivePort){
    		this.sendPort = sendPort;
    		this.receivePort = receivePort;
    	}
    	
    	@Override
    	public void run(){
    		try {
    			sendServerSocket = new ServerSocket(sendPort);
    			receiveServerSocket = new ServerSocket(receivePort);
    		} catch (IOException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    		
    		while(true){//Loops keeps going trying to reconnect to Clients if they get disconnected
    			try{
    				
    				byte[] byteBuffer = new byte[256];
    				int recvMsgSize= 0;			
    				Socket receivingSocket = receiveServerSocket.accept();
    				Socket sendingSocket = sendServerSocket.accept();
    				
    				InputStream in = receivingSocket.getInputStream();
    				OutputStream out = sendingSocket.getOutputStream();
    				
    				try{ 
    					while((recvMsgSize = in.read(byteBuffer)) != -1)//reads the InputStream to the byteBuffer until a disconnect signal is received (-1 is received)
    					{
    						out.write(byteBuffer,0,recvMsgSize);//Writes the byteBuffer to the OutputStream
    					}
    				}catch(SocketException e){
    					System.out.println(name + ": Client Disconnected Abruptly");					
    				}
    				//After Disconnection, close the send and receive sockets.
    				receivingSocket.close();
    				sendingSocket.close();
    				
    			
    			}
    			catch(Exception e){
    				//If an exception is caught while creating sockets, break  the loop and print errors
    				e.printStackTrace();
    				break;
    			}
    		}
    		
    	}
    	
    
    }
    Java Code:
    //***********CLIENT*******************
    
    public class Client1 {
    	private final static String serversIP = "192.168.1.132";
    	private final static int sendPort = 1009, receivePort = sendPort+100;
    	
    	public static void main(String[] args) {
    		System.out.println(sendPort + " " + receivePort);
    		Thread sender = new Thread(new Sender(serversIP, sendPort));
    		Thread receiver = new Thread(new Receiver(serversIP, receivePort));
    		
    		sender.start();
    		receiver.start();
    		
    		
    		
    	}
    
    }
    Java Code:
    ////////////Client Sender Thread
    import java.io.IOException;
    import java.io.OutputStream;
    //import java.net.ConnectException;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    
    public class Sender implements Runnable{
    	private int port;
    	private String ip;
    	
    	public Sender(String ip,int port){
    		this.port = port;
    		this.ip = ip;
    	}
    	@Override
    	public void run() {
    		Socket socket;
    		int i = 0;
    		while(true){
    		
    			try {
    				socket = new Socket(ip, port);
    				while(true){
    					i++;
    					String message = "Looped " + i + " times\n";
    					byte[] byteBuffer = message.getBytes();
    					
    					OutputStream out = socket.getOutputStream();
    					out.write(byteBuffer);
    					Thread.sleep(100);
    				}
    			} catch (UnknownHostException e) {
    				e.printStackTrace();
    			} catch (IOException e) {
    				System.out.println("Connection Refused by Server");
    			} catch (InterruptedException e) {
    				System.out.println("Thread was unable to sleep");
    			}
    		}	
    		
    	}
    
    }
    Java Code:
    ///////////Receiver - Client Side thread
    import java.net.*;
    import java.io.*;
    
    
    public class Receiver implements Runnable{
    	private int port;
    	private String ip;
    	public Receiver(String ip,int port){
    		this.port = port;
    		this.ip   = ip;
    	}
    	@Override
    	public void run() {
    		Socket socket;
    		byte[] byteBuffer = new byte[256];
    		while(true){
    			try {
    					Thread.sleep(100);
    					socket = new Socket(ip, port);
    					InputStream in = socket.getInputStream();
    					//OutputStream out = socket.getOutputStream();
    					
    					try{
    						//out.write("alive".getBytes());
    						while(true){
    							Thread.sleep(100);
    							in.read(byteBuffer);
    							String received = new String(byteBuffer);
    							System.out.println(received);
    						}
    					}catch(SocketException e){
    							System.out.println("Socket Exception");
    					}
    					socket.close();
    					
    			} catch (UnknownHostException e) {
    				e.printStackTrace();
    			} catch (IOException e) {
    				System.out.println("Connection refused");
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    		
    	}
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default Re: TCP Two-Client-Server/Client Program not doing what I expected


  3. #3
    xenoepist is offline Xenoepist
    Join Date
    Jan 2012
    Location
    Brownsville, Tx
    Posts
    5
    Rep Power
    0

    Default Re: TCP Two-Client-Server/Client Program not doing what I expected

    I know, I did it by mistake, but I don't know how to erase one of the Threads... sorry! :/

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default Re: TCP Two-Client-Server/Client Program not doing what I expected

    You cross posted here and at Dev Shed by mistake?

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  5. #5
    xenoepist is offline Xenoepist
    Join Date
    Jan 2012
    Location
    Brownsville, Tx
    Posts
    5
    Rep Power
    0

    Default Re: TCP Two-Client-Server/Client Program not doing what I expected

    Oh, no! I misunderstood. What I meant to say is that I posted the thread twice in here by mistake and I was trying to erase one of the threads. I did posted the thread here and Devshed on purpose. Is there anything wrong with me posting the same question on both forums?

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default Re: TCP Two-Client-Server/Client Program not doing what I expected

    No and Yes.
    As long as you provide links to the other sites so all can see the progress of the problem, there is no problem.
    None of the volunteers like answering a question that has already been answered. Big waste of time.

  7. #7
    xenoepist is offline Xenoepist
    Join Date
    Jan 2012
    Location
    Brownsville, Tx
    Posts
    5
    Rep Power
    0

    Default Re: TCP Two-Client-Server/Client Program not doing what I expected

    I understand, I'll do that in the future

Similar Threads

  1. Simple Client (2) - Server program
    By Reztem in forum New To Java
    Replies: 2
    Last Post: 01-09-2012, 02:05 AM
  2. Really big problem in client and server program
    By helioshilary in forum New To Java
    Replies: 14
    Last Post: 07-13-2011, 01:17 PM
  3. Really big problem in client and server program
    By helioshilary in forum New To Java
    Replies: 0
    Last Post: 07-12-2011, 06:08 PM
  4. Replies: 1
    Last Post: 10-05-2008, 03:12 PM
  5. Identify Client in Socket Client Server Application
    By masadjie in forum Networking
    Replies: 1
    Last Post: 12-20-2007, 09:18 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •