CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2016
    Posts
    1

    Multiple CLients, Single server, No threading

    I am attempting to to run multiple clients with single server, without using athreading. My logic is as follows, use different port numbers for each client.
    I have been successful in running a single server-single client system.
    I am posting the code below.

    How do I fix the code to incorporate multiple clients.

    Code:
    package tcpmsg;
    
    import java.io.*;
    import java.net.*;
    class TCPClient
    {
    	public static void main(String argv[]) throws Exception
    	{
    		String sentence;
    		String modifiedSentence;
    
    		BufferedReader inFromUser=
    			new BufferedReader(new InputStreamReader(System.in));
    
    		InetAddress inetAddress=InetAddress.getLocalHost();
    		//.getByName(String hostname); "CL11"
    		System.out.println(inetAddress);
    
    		Socket clientSocket = new Socket(inetAddress,6789);
    		DataOutputStream outToServer=
    			new  DataOutputStream(clientSocket.getOutputStream());
    
    		BufferedReader inFromServer=
    			new  BufferedReader(new InputStreamReader
    							(clientSocket.getInputStream()));
    
    		sentence=inFromUser.readLine();
    		outToServer.writeBytes(sentence+'\n');
    
    		modifiedSentence=inFromServer.readLine();
    		System.out.println("From Server: "+modifiedSentence );
    		clientSocket.close();
    	}
    }
    Code:
    import java.io.*;
    import java.net.*;
    
    class TCPServer
    {
    	public static void main(String argv[]) throws Exception
    	{
    		String clientSentence;
    		String capitalizedSentence;
    		ServerSocket welcomeSocket= new ServerSocket(6789);
    		while (true)
    		{
    			Socket connectionSocket=welcomeSocket.accept();
    			BufferedReader inFromClient=
    				new BufferedReader(new InputStreamReader(
    					connectionSocket.getInputStream()));
    			DataOutputStream outToClient=
    				new DataOutputStream(
    					connectionSocket.getOutputStream());
    			clientSentence=inFromClient.readLine();
    			System.out.println("From Client: "+clientSentence);
    			capitalizedSentence=
    				clientSentence.toUpperCase()+'\n';
    
    			outToClient.writeBytes(capitalizedSentence);
    			
    		}
    	}
    }
    Last edited by 2kaud; November 27th, 2016 at 09:39 AM. Reason: Code tags added

  2. #2
    Join Date
    Jun 1999
    Location
    Eastern Florida
    Posts
    3,877

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured