Home Java javaTutorial Detailed explanation of network programming socket

Detailed explanation of network programming socket

May 08, 2017 pm 02:04 PM
java socket network programming

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();
  }
 }
}
Copy after login

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();
  }
 }
}
Copy after login

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...
Copy after login

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!
Copy after login

【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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

How to convert XML to PDF on your phone? How to convert XML to PDF on your phone? Apr 02, 2025 pm 10:18 PM

It is not easy to convert XML to PDF directly on your phone, but it can be achieved with the help of cloud services. It is recommended to use a lightweight mobile app to upload XML files and receive generated PDFs, and convert them with cloud APIs. Cloud APIs use serverless computing services, and choosing the right platform is crucial. Complexity, error handling, security, and optimization strategies need to be considered when handling XML parsing and PDF generation. The entire process requires the front-end app and the back-end API to work together, and it requires some understanding of a variety of technologies.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles