• Advertisement
Sign in to follow this  

[java] establishing client

This topic is 4837 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I want to do simple multi-client server/client program. I already done the server side, and I dont know how to make the client class. This is my multi-client server:
import java.io.*;
import java.net.*;

public class server
{	public static void main(String[] args)
	{	int i=1;
		try
		{	ServerSocket s = new ServerSocket(27001);  //establish a server
			while(true)
			{	Socket incoming = s.accept();          //waiting for "i" client
				System.out.println(" Spawning " + i); 
				new ThreadedEchoHandler(incoming, i).start();
				i++;
			}
		}
		catch(Exception e)
		{	System.out.println(e);
		}
	}
}

class ThreadedEchoHandler extends Thread
{	private Socket incoming;
	private int counter;
	
	public ThreadedEchoHandler(Socket i, int c)
	{	incoming = i;
		counter  = c;
	}
	public void run()
	{	try
		{	BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
			PrintWriter out = new PrintWriter(incoming.getOutputStream(), true); //autoFlush
			out.println("Hello! Enter 'x' for exit");
			boolean done = false;
			while(!done)
			{	String str = in.readLine();
				if(str == null)	done = true;
				else
				{	out.println("Echo (" + counter + "): " + str);
					
					if(str.trim().equals("x"))
					done = true;    	
				}
			}
			incoming.close();
		}
		catch(Exception e)
		{	System.out.println(e);
		}
	}
} 

How can I create client ? THANKS

Share this post


Link to post
Share on other sites
Advertisement
Just write a second class that opens a Socket object pointing to the host and port that you specify the ServerSocket to listen on (for example, if you are running this on your own machine, point the client apps Socket object to 127.0.0.1 and port 27001).

Simple as that. Java Network Programming, 2nd Edition is a pretty good guide to all things java.net.*, so I would recommend grabbing a copy.

Share this post


Link to post
Share on other sites
I want my server to print the string client sending him. I dont understand why its not happening. This is my client:


import java.net.*;
import java.io.*;

public class client
{ public static void main(String[] args)
{
try
{ Socket s = new Socket("", 27001);
PrintWriter out = new PrintWriter(s.getOutputStream());
out.print("Server hello!");
}
catch(Exception e)
{ System.out.println(e);
}
}

}




Share this post


Link to post
Share on other sites
Use:

catch(IOException e) {
e.printStackTrace();
}



Then look at the stack trace. It will show line numbers in your code. Look at those lines to try and figure it out.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement