MAKING TCP CONNECTION
These classes are related to making normal TCP connections:
1.ServerSocket
2.Socket
ServerSocket represents the socket on a server that waits and listens for requests for service from a
client.Socket represents the endpoints for communication between a server and a client. When a server
gets a request for service, it creates a Socket for communication with the client and continues to listen
for other requests on the ServerSocket. The client also creates a Socket for communication with the
server.
Simple Server Client Messaging Using TCP
Server Side Program
// Import Java Packages
import java.net.*;
import java.lang.*;
import java.io.*;
public class Server{
//port number should be more than 1024
public static final int PORT = 1025;
public static void main( String args[])
{
ServerSocket sersock = null;
Socket sock = null;
System.out.println(" Wait !! ");
try
{
// Initialising the ServerSocket
sersock = new ServerSocket(PORT);
// Gives the Server Details Machine name,Port number
System.out.println("Server Started :"+sersock);
try
{
/* makes a socket connection to particular client after
which two way communication take place */
sock = sersock.accept();
System.out.println("Client Connected :"+ sock);
// Receive message from client i.e Request from client
DataInputStream ins = new DataInputStream(sock.getInputStream());
// Send message to the client i.e Response
PrintStream ios = new PrintStream(sock.getOutputStream());
ios.println("Hello from server");
ios.close();
// Close the Socket connection
sock.close();
}
catch(SocketException se)
{
System.out.println("Server Socket
problem "+se.getMessage());
}
catch(Exception e)
{
System.out.println("Couldn't start "
+ e.getMessage()) ;
}
// Usage of some methods in Socket class
System.out.println(" Connection from : " +
sock.getInetAddress());
}
}
Saturday, January 7, 2012
TCP Server side Code Java Part 1
Posted by
Unknown
at
2:57 AM
Labels: Basic, Networking, TCP
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment