SDSU CS 596 Client-Server Programming
Java Network Q and A

[To Lecture Notes Index]
San Diego State University -- This page last updated March 5, 1996
----------

Contents of Java Network Q and A Lecture

    1. Java Networking Q and A
      1. Q - How Do I open a Socket?
      2. Q - How do I use a Socket to communicate with a Server or Client?
      3. Q - How do I get the input and output streams from a socket?
      4. Q - How do I read from an input stream?
      5. Q - How do I write to an output stream?
      6. Q - What do I send between the Client and Server?

Java Networking Q and A


Q - How Do I open a Socket?


In a client:
	Socket	aSocket = null;

	aSocket = new Socket(serverName, portNumber);


In a server:
	ServerSocket  aSocket = null;

	try 
		{
		aSocket = new ServerSocket(  portNumber  );
		} 
	catch (IOException e)


Q - How do I use a Socket to communicate with a Server or Client?


Step 1
Get the input and/or output streams from the socket

Step 2
Read the input stream if you are excepting data
Write to the output stream if you need to send data


Q - How do I get the input and output streams from a socket?


	InputStream  in  =  aSocket.getInputStream();
	OutputStream  out  =  aSocket.getOutputStream();

Q - How do I read from an input stream?


There are various ways. Here is one way to read from an input stream that is connected to a socket. You can also deal with bytes.

	InputStream  in  =  aSocket.getInputStream();
	// Buffering is a good idea when dealing with a network
	BufferedInputStream  bufferedIn; 
	bufferedIn  =  new BufferedInputStream(  bufferedIn  );

	// ASCIIInputStream make is easy to read from the stream
	ASCIIInputStream  cin;
	cin  = new ASCIIInputStream( bufferedIn  );

Now you can use any of the ASCIIInputStream methods like readLine() and readInt()
	String  message  =  cin.readLine();


Q - How do I write to an output stream?


There are various ways. Here is one way to write to an output stream that is connected to a socket.

	OutputStream  out  =  aSocket.getOutputStream();
	// Buffering is a good idea when dealing with a network
	BufferedOutputStream  bufferedOut; 
	bufferedOut  =  new BufferedOutputStream(  bufferedOut  );

	// PrintStream make is easy to write to a stream
	PrintStream  cout;
	cout  = new PrintStream( bufferedOut,  false  );

Now you can use the PrintStream methods print() and println().
	cout.println( " Hi Mom" );


The false in the printstream constructor turns auto-flushing off. If you want to force a message to be sent you need to flush the buffer via:
	cout.flush();

Q - What do I send between the Client and Server?


What do you want them to do?
----------