[Tutorial] Networking: Sockets and ServerSockets
Author |
Message |
rizzix
|
Posted: Sun Mar 13, 2005 7:27 pm Post subject: [Tutorial] Networking: Sockets and ServerSockets |
|
|
The Java networking model is based of the BSD network model, as do most network APIs. This basically invovles the idea of Sockets which are communication points on your computers. A program creates socket of either a client or server type. The server socket establishes a listening port on a computer. The cleint sockets establishes a listening port and connects it self to a server socket. Upon a successful connection attempt the server socket is required to accept the connection, after which a two-way communication system is established. The classes required for networking are in the java.net package. It may be helpful to know that the Socket clases encapsulates the TCP protocol.
ServerSocket
The methods/constuctors you should be aware of:
ServerSocket(int port);
This is one of the 4 constuctors and the most commonly used
Socket accept();
This method is called, to listen for a client
void close();
Close the bounded connection
Socket
The methods/constuctors you should be aware of:
Socket(String host, int port);
This is one of 7 constuctors and the most commmonly used
boolean isConnected();
Returns true if connected
InputStream getInputStream();
Returns the InputStream for reading data
OutputStream getOutputStream()
Returns the OutputStream for writing data
void close();
Closes the connection to server
Example Java: | import java.net.*;
import java.io.*;
| Both of the follwing class will require the above importsIn the client program we read data from Terminal and print it to the server connected on localhost at port 5060. Knowledge on Streams is assumed, so I will not explain the whys and hows related to the in and serverOut Character streams. But basically after establishing a connection we get the output stream of the server, then we read the input from terminal and quit upon reading "__END__". This input is then printed through the Buffered PrintWriter serverOut. Note that since the stream is buffered it is necessary to flush it, for the data to be sent. Note that it is important to close the connection to the server.
Java: | class TestServer {
public static void main (String[] args ) {
try {
Socket client; BufferedReader clientIn; String input;
// bind ServerSocket to localhost at port 5060
ServerSocket connection = new ServerSocket(5060);
while (true) {
// accept client connections
client = connection. accept();
// establish an input stream with client
clientIn = new BufferedReader(
new InputStreamReader(client. getInputStream())
);
// read Strings from client's InputStream
while ((input = clientIn. readLine()) != null)
System. out. println(input ); // echo until disconnect
break; // work with only one client
}
connection. close(); // close connection
} catch (Exception e ) {
System. out. println(e );
}
}
} | The server program we establish a listening socket (ServerSocket) on localhost at port 5060. Then we call the Socket accept() method of the connection, which waits on the current thread (i.e the thread stops from futher execution) until it recieves a client connection. When a client connects a socket is returned which represents the connection to the client. The while-loop is an infinite loop, that should keep waiting for clients and start new threads to handle each client individually. But in our case we work with only one client hence the break at the end of the loop (we could have simply removed the loop altogether). Then we attain and establish a Character input stream of the client socket. The next while-loop reads data (inclusive of error checking) and writes it to Terminal. The String readLine() method will retun null if the client disconnects, hence the error checking. After all the echoing, we close the ServerSocket connection. |
|
|
|
|
|
Sponsor Sponsor
|
|
|
Krabjuice
|
Posted: Thu Mar 16, 2006 5:04 pm Post subject: Re: [Tutorial] Networking: Sockets and ServerSockets |
|
|
Built on the code above, this server allows connections from a user definable amount of clients. However, there are limitations on this specific server: ie: It expects the first client to respond before the second, and the second client before the third..and so on. Another minus is that the server must be "full" before it can start recieving from the clients. A start, perhaps.
It works with the above client.
Java: | import java.net.*;
import java.util.*;
import java.io.*;
class ServerArray {
public static void main (String[] args ) {
System. out. println("Server up");
System. out. println("How many clients?");
Scanner get = new Scanner (System. in);
int clientnumber = get. nextInt();
get. close();
System. out. println("Looking for clients");
try
{
Socket[] client = new Socket[clientnumber ];
BufferedReader[] clientIn= new BufferedReader [clientnumber ];
String[] input= new String [clientnumber ];
// bind ServerSocket to localhost at port 5060
ServerSocket connection = new ServerSocket(5060);
//while (true)
//{
for (int i= 0;i<= (clientnumber - 1);i++ )
{
// accept client connections
client [i ] = connection. accept();
System. out. println("Found a client #"+i );
}
while (true)
{
for (int j= 0;j<=clientnumber- 1;j++ )
{
clientIn [j ] = new BufferedReader(new InputStreamReader(client [j ]. getInputStream()));
if ((input [j ] = clientIn [j ]. readLine()) != null)
{
System. out. println(input [j ]);
}
}
}
//}
//connection.close();
}
catch (Exception e )
{
System. out. println(e );
}
}
} |
Note, this will not compile in Ready. It requires a IDE running on the latest JDK. Java 1.4 won't work, 1.5 will.
Oh--and i'm back, bitches. |
|
|
|
|
|
JMG
|
Posted: Sun Feb 24, 2008 2:10 am Post subject: RE:[Tutorial] Networking: Sockets and ServerSockets |
|
|
thanx to both. really helpful |
|
|
|
|
|
|
|