Link to home
Start Free TrialLog in
Avatar of eugene007
eugene007

asked on

Sockets

I have written a simple client server program using sockets. There is no compilation and run time error. However the application does not seem to do the logics I have written. Did I miss something?.
Client
-------
 
import java.io.*;
import java.net.*;
 
public class Client
{
	Socket s;
	PrintWriter out;
	BufferedReader in;
	
	public Client()
	{
		try
		{ 
	        s = new Socket("127.0.0.1",1418);
	        out = new PrintWriter(s.getOutputStream());
	        in = new BufferedReader(new InputStreamReader(s.getInputStream()));
	        out.write("Hi");
	        String m = in.readLine();
	        System.out.println(m);
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
	 
    public static void main(String[] args) 
    {
        Client m = new Client();
    }
}
 
 
Server
---------
 
public class Server 
{
	PrintWriter out;
	BufferedReader in;
	ServerSocket ss;
	Socket sc;
	
	public Server()
	{
		try
		{
			ss = new ServerSocket(1418);
			sc = ss.accept();
			out = new PrintWriter(sc.getOutputStream());
			in = new BufferedReader(new InputStreamReader(sc.getInputStream()));
			String m = in.readLine();
			out.write(m);
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
	
    public static void main(String[] args) 
    {
    	Server s = new Server();
    }
}

Open in new window

SOLUTION
Avatar of ozlevanon
ozlevanon

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of eugene007
eugene007

ASKER

I tried and it does not work.
Also I switched write() method to println() method.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Now it works. This is quite odd. I need to flush the data even when im using the println() method to write.
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
so the purpose of the flush() method is to ensure that what is written are commited.
>>so the purpose of the flush() method is to ensure that what is written are commited.

No. It's in no way transactional. There's no 'rollback' for instance. And when you close(), it will get flushed automatically.

Its purpose is to transfer what's held in the buffers to the stream immediately
:-)