Socket programming
Sockets use TCP to provide a mechanism for communication between two computers. The client program creates a socket and tries to connect to the server's socket.
When the connection is established, the server creates a Socket object. The client and server can now communicate by writing and reading to the Socket object.
The Java.net.Socket class represents a socket, and the Java.net.ServerSocket class provides a mechanism for the server program to listen to the client and establish a connection with them.
The following steps occur when a TCP connection is established between two computers using sockets:
The server instantiates a ServerSocket object that communicates through the port on the server.
The server calls the Accept () method of the ServerSocket class, and the method waits until the client connects to the given port on the server.
When the server is waiting, a client instantiates a Socket object, specifying the server name and port number to request a connection.
The constructor of the Socket class attempts to connect the client to the specified server and port number. If the communication is established, a Socket object is created on the client to communicate with the server.
On the server side, the Accept () method returns a new socket reference to the server that is connected to the client's socket.
After the connection is established, each socket has an output stream and an input stream through the use of an I/O stream, and the client's output Beijing stock is connected to the server-side input stream, and the client's input is hooked to the server-side output stream.
TCP is a two-way communication protocol, so data can be sent over two data streams at the same time. Here are some classes that provide a complete set of useful ways to implement a socket.
Methods of the ServerSocket class
The server application obtains a port by using the Java.net.ServerSocket class and listens for client requests.
The ServerSocket class has four methods of construction:
Ordinal method Description
1 public serversocket (int port) throws IOException
Creates a server socket bound to a specific port.
2 public serversocket (int port, int backlog) throws IOException
Creates a server socket with the specified backlog and binds it to the specified local port number.
3 public serversocket (int port, int backlog, inetaddress address) throws IOException
Creates a server using the specified port, the listener backlog, and the local IP address to bind to.
4 public ServerSocket () throws IOException
Create a non-binding server socket.
Create a non-binding server socket. If the ServerSocket constructor method does not throw an exception, it means that your application has successfully bound to the specified port and listens for client requests.
Here are some common methods for ServerSocket classes:
Ordinal method Description
1 public int Getlocalport ()
Returns the port on which this socket listens.
2 public Socket Accept () throws IOException
Listens for and accepts connections to this socket.
3 public void Setsotimeout (int timeout)
Enables/disables so_timeout, in milliseconds, by specifying a time-out value.
4 public void bind (socketaddress host, int backlog)
Bind the ServerSocket to a specific address (IP address and port number).
Method of Socket Class
The Java.net.Socket class represents a socket that both the client and the server use to communicate with each other. The client wants to get a socket object by instantiating it, and the server obtains a socket object through the Accept () method's return value.
The Socket class has five constructor methods.
Ordinal method Description
1 public Socket (String host, int port) throws Unknownhostexception, IOException.
Creates a stream socket and connects it to the specified port number on the specified host.
2 Public Socket (inetaddress host, int port) throws IOException
Creates a stream socket and connects it to the specified port number for the specified IP address.
3 Public sockets (String host, int port, inetaddress localaddress, int localport) throws IOException.
Creates a socket and connects it to the specified remote port on the specified remote host.
4 Public sockets (inetaddress host, int port, inetaddress localaddress, int localport) throws IOException.
Creates a socket and connects it to the specified remote port on the specified remote address.
5 Public sockets ()
Create an SocketImpl socket from the system default type
When the socket construction method returns, and does not simply instantiate a socket object, it will actually attempt to connect to the specified server and port.
Here are some interesting ways to note that both the client and server side have a Socket object, so the methods can be invoked both by the client and the service side.
Ordinal method Description
1 public void Connect (socketaddress host, int timeout) throws IOException
Connect this socket to the server and specify a timeout value.
2 public inetaddress getinetaddress ()
Returns the address of the socket connection.
3 public int Getport ()
Returns the remote port that this socket is connected to.
4 public int Getlocalport ()
Returns the local port to which this socket is bound.
5 public socketaddress getremotesocketaddress ()
Returns the address of the endpoint for this socket connection, or null if not connected.
6 Public InputStream getInputStream () throws IOException
Returns the input stream for this socket.
7 public OutputStream Getoutputstream () throws IOException
Returns the output stream for this socket.
8 public void Close () throws IOException
Close the socket.
Methods of the InetAddress class
This class represents an Internet Protocol (IP) address. The following is a list of the more useful methods for Socket programming:
Ordinal method Description
1 static inetaddress getbyaddress (byte[] addr)
Returns the InetAddress object, given the original IP address.
2 static inetaddress getbyaddress (String host, byte[] addr)
Create inetaddress based on the hostname and IP address of the Kim that provides the melt.
3 static inetaddress Getbyname (String host)
Determines the IP address of the host in the given host name.
4 String gethostaddress ()
Returns the IP address string (in text representation).
5 String GetHostName ()
Gets the host name for this IP address.
6 static inetaddress Getlocalhost ()
Returns the local host.
7 String toString ()
Convert this IP address to a String.
Socket Client Instance
The following greetingclient is a client program that connects to the server via the socket and sends a request, and then waits for a response.
Greetingclient.java File Code:
File name Greetingclient.java
Import java.net. ;
Import java.io.;
public class Greetingclient
{
public static void Main (String [] args)
{
String serverName = args[0];
int port = integer.parseint (args[1]);
Try
{
SYSTEM.OUT.PRINTLN ("Connect to Host:" + ServerName + ", port number:" + port);
Socket client = new socket (serverName, port);
SYSTEM.OUT.PRINTLN ("Remote host Address:" + client.getremotesocketaddress ());
OutputStream outtoserver = Client.getoutputstream ();
DataOutputStream out = new DataOutputStream (outtoserver);
out.writeUTF("Hello from " + client.getLocalSocketAddress()); InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); System.bjrongjinhuiyin.com.out.println("服务器响应: " + in.readUTF()); client.close(); }catch(IOException e) { e.printStackTrace(); }
}
}
Socket Service-side instance
The Greetingserver program below is a server-side application that uses a Socket to listen on a specified port.
Greetingserver.java File Code:
File name Greetingserver.java
Import java.net. ;
Import java.io.;
public class Greetingserver extends Thread
{
Private ServerSocket ServerSocket;
public greetingserver (int port) throws IOException
{
ServerSocket = new ServerSocket (port);
Serversocket.setsotimeout (10000);
}
public void Run ()
{
while (true)
{
Try
{
System.out.println ("Wait for remote connection, port number:" + serversocket.getlocalport () + "...");
Socket Server = Serversocket.accept ();
SYSTEM.OUT.PRINTLN ("Remote host Address:" + server.getremotesocketaddress ());
DataInputStream in = new DataInputStream (Server.getinputstream ());
System.out.println (In.readutf ());
DataOutputStream out = new DataOutputStream (Server.getoutputstream ());
Out.writeutf ("Thank You for connecting me:" + server.getlocalsocketaddress () + "\ngoodbye!");
Server.close ();
}catch (sockettimeoutexception s)
{
System.out.println ("Socket timed out!");
Break
}catch (IOException e)
{
E.printstacktrace ();
Break
}
}
}
public static void Main (String [] args)
{
int port = integer.parseint (Args[0]);
Try
{
Thread t = new greetingserver (port);
T.run ();
}catch (IOException e)
{
E.printstacktrace ();
}
}
}
Java Network Programming