Sign in to follow this  
cpp_boy

[java] establishing client

Recommended Posts

cpp_boy    100
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
aidan_walsh    739
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
cpp_boy    100
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this