Home  >  Article  >  Java  >  Detailed explanation of network programming socket

Detailed explanation of network programming socket

Y2J
Y2JOriginal
2017-05-08 14:04:481273browse

This article mainly introduces the class methods and examples in java network programming. Friends who need it can refer to it

Network programming refers to writing programs that run on multiple devices (computers). These devices All connected through the Internet.

The J2SE API in the java.net package contains classes and interfaces that provide low-level communication details. You can use these classes and interfaces directly to focus on solving problems rather than on communication details.

The java.net package provides support for two common network protocols:

TCP: TCP is the abbreviation of Transmission Control Protocol. It guarantees reliable communication between two applications. Commonly used for Internet protocols, known as TCP/IP.

UDP:UDP is the abbreviation of User Datagram Protocol, a connectionless protocol. Provides packets of data to be sent between applications.
This tutorial mainly explains the following two topics.

Socket Programming: This is the most widely used networking concept and it has been explained in great detail

URL Handling: This part will be discussed in another space. Click here to learn more about URL processing in Java language.

Socket Programming

Sockets provide a communication mechanism between two computers using TCP. The client program creates a socket and attempts to connect to the server's socket.

When the connection is established, the server will create a Socket object. The client and server can now communicate by writing to and reading from the Socket object.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for server programs to listen to clients and establish connections with them.

The following steps occur when establishing a TCP connection using sockets between two computers:

The server instantiates a ServerSocket object that represents the port on the server. communication.

The server calls the accept() method of the ServerSocket class, which will wait until the client connects to the given port on the server.

While the server is waiting, a client instantiates a Socket object and specifies 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 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 socketreference on the server, which is connected to the client's socket.

After the connection is established, communication is carried out using I/O streams. Each socket has an output stream and an input stream. The client's output stream is connected to the server's input stream, and the client's input stream is connected to the server's output stream.

TCP is a two-way communication protocol, so data can be sent through two data streams at the same time. The following is a complete set of useful methods provided by some classes to implement sockets.

Methods of 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 construction methods:

1234

Create an unbound server socket. If the ServerSocket construction method does not throw an exception, it means that your application has successfully bound to the specified port and is listening for client requests.

Here are some common methods of the ServerSocket class:

## Serial number Method description
public ServerSocket(int port) throws IOException

Create a server socket bound to a specific port

public ServerSocket(int port, int backlog) throws IOException

Use the specified backlog to create a server socket and bind it to the specified local port number

public ServerSocket(int port, int backlog, InetAddress address) throws IOException

Create a server with the specified port, listening backlog, and local IP address to bind to

public ServerSocket() throws IOException

Create an unbound server socket

##1## public int getLocalPort()234Methods of the Socket class
Serial number Method description

Return this socket The port the word is listening on

##public Socket accept() throws IOException Listen and accept Connection to this socket

public void setSoTimeout(int timeout) Enabled by specifying a timeout value /Disable SO_TIMEOUT in milliseconds

public void bind(SocketAddress host, int backlog) will ServerSocket binds to a specific address (IP address and port number)

The java.net.Socket class represents the socket used by both clients and servers to communicate with each other. The client obtains a Socket object through instantiation, and the server obtains a Socket object through the return value of the accept() method.


The Socket class has five construction methods.


##Serial number##public Socket(String host, int port) throws UnknownHostException, IOException. Create a stream socket and connect it to the specified port number on the specified host public Socket( InetAddress host, int port) throws IOExceptionCreates a stream socket and connects it to the specified port number of the specified IP addresspublic Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException.Create a socket and connect it to the specified remote port on the specified remote hostpublic Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOExceptionCreate a socket Socket and connect it to the specified remote port on the specified remote addresspublic Socket() Create an unconnected socket through the system default type SocketImpl
Method description ##1

2

3

4

5

When the Socket constructor returns, it does not simply instantiate a Socket object, it will actually try to connect to the specified server and port.

Some interesting methods are listed below. Note that both the client and the server have a Socket object, so both the client and the server can call these methods.

# #12345 678
Serial number Method description
public void connect(SocketAddress host, int timeout) throws IOException

Connect this socket to the server and specify a timeout value

public InetAddress getInetAddress()

Returns the address of the socket connection

public int getPort()

Returns the remote port to which this socket is connected

public int getLocalPort()

Returns the local port this socket is bound to

public SocketAddress getRemoteSocketAddress()

Returns the address of the endpoint connected to this socket, or null if not connected


public InputStream getInputStream() throws IOException

Returns the input stream of this socket

public OutputStream getOutputStream() throws IOException

Returns the output stream of this socket

public void close() throws IOException

Close this 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:


12345##67

Socket client example

The following GreetingClient is a client program that connects to the server through socket and sends a request, and then waits for a response.

// 文件名 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("Connecting to " + serverName
        + " on port " + port);
   Socket client = new Socket(serverName, port);
   System.out.println("Just connected to "
      + 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.out.println("Server says " + in.readUTF());
   client.close();
  }catch(IOException e)
  {
   e.printStackTrace();
  }
 }
}

Socket Server Example

The following GreetingServer program is a server-side application that uses Socket to listen to a specified port.

// 文件名 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("Waiting for client on port " +
   serverSocket.getLocalPort() + "...");
   Socket server = serverSocket.accept();
   System.out.println("Just connected to "
     + 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 to "
    + 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.start();
  }catch(IOException e)
  {
   e.printStackTrace();
  }
 }
}

Compile the above java code, and execute the following command to start the service, using the port number 6066:

$ java GreetingServer 6066
Waiting for client on port 6066...

Open the client as follows:

$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!

【Related Recommendations】

1.Java Free Video Tutorial

2.Java implements equal proportions of pictures Thumbnail video tutorial

3.Alibaba Java Development Manual

Serial number Method description

static InetAddress getByAddress(byte[] addr)

At the given original IP address In the case of , return the InetAddress object

static InetAddress getByAddress(String host, byte[] addr)

Create an InetAddress based on the provided hostname and IP address

static InetAddress getByName(String host)


Determine the IP address of a host given a hostname

String getHostAddress()

Return IP Address

String(in text representation)

String getHostName()

Get the host name of this IP address

##static InetAddress getLocalHost()

Return local host

String toString() Convert this IP address to String

The above is the detailed content of Detailed explanation of network programming socket. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn