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
- Java Networking Q and A
- Q - How Do I open a Socket?
- Q - How do I use a Socket to communicate with a Server or Client?
- Q - How do I get the input and output streams from a socket?
- Q - How do I read from an input stream?
- Q - How do I write to an output stream?
- Q - What do I send between the Client and Server?
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)
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
InputStream in = aSocket.getInputStream();
OutputStream out = aSocket.getOutputStream();
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();
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();
What do you want them to do?