Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

12.4-full Stack Java Notes: Java Network programming (2)

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Socket Programming and Communication Based on TCP Protocol

In network communication, the program that initiates communication for the first time is called a client program, and the program waiting for connection in the first communication is called a server program. Once communication is established, the client and server are exactly the same, with no essential differences.

"request-response" mode:

Socket class: Send TCP messages

ServerSocket class: Creating a server

Sockets are a mechanism for exchanging data between processes. These processes can be on the same machine or on different machines connected by a network. In other words, sockets function as communication endpoints. A single socket is an endpoint, while a pair of sockets form a bidirectional communication channel that allows unrelated processes to exchange data locally or over the network. Once a socket connection is established, data can be sent bidirectionally or unidirectionally in the same or different systems until one of the endpoints closes the connection. Sockets are associated with host addresses and port addresses.

A host address is the IP address of the host on which the client or server program resides. A port address is the communication port of the host used by the client or server program. In the client and server, create independent Sockets respectively, and connect the two Sockets through the attributes of Sockets. In this way, the client and server communicate through the connection established by sockets using input and output streams.

TCP/IP sockets are the most reliable bi-directional streaming protocol, and any amount of data can be sent using TCP/IP. Sockets are really just numbered ports on a computer. If the sender and receiver computers determine the port, they can communicate.

Simple procedure for TCP/IP communication connection:

TCP/IP software on computer A sends a message to computer B containing the port number, and computer B's TCP/IP software receives the message and checks to see if any programs it knows are receiving messages on that port. If so, he passes the message to the program.

For the program to run effectively, there must be a client and a server.

Programming order through Socket:

1. Create ServerSocket, define the listening port of ServerSocket (receive messages from client on this port!)

ServerSocket calls the accept() method to put it in a blocking state

3. Create client Socket and set IP and port of server

4. The client sends a connection request to establish a connection.

5. Get the InputStream and OutputStream of the Server and Client Socket, respectively

6. Data transmission using Socket and ServerSocket.

[Example 1] One-way communication server-side code

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.OutputStreamWriter;

import java.net.ServerSocket;

import java.net.Socket;

/**

* The simplest server-side code

* @author Administrator

*

*/

public class BasicSocketServer {

public static void main(String[] args) {

try {

//Create server-side socket

ServerSocket serverSocket = new ServerSocket(8888); //How many TCP ports are there??

//Listen, wait for client requests, and be willing to accept connections.

System.out.println("Server set up listening");

Socket socket = serverSocket.accept();

//Send data to client via stream

// ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

// oos.writeObject("aaaaa");

// oos.close();

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

bw.write("hhhh");

bw.close();

socket.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

[Example 2] One-way communication Socket client code

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.InetAddress;

import java.net.Socket;

/**

* The simplest Socket client

* @author Administrator

*

*/

public class BasicSocketClient {

public static void main(String[] args) {

try {

//Specify the IP and port of the server to which you want to connect. Not your own machine. The sending port is random.

Socket socket = new Socket(InetAddress.getLocalHost(),8888);

// ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

// String string = (String) ois.readObject();

// System.out.println(string);

BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

System.out.println(br.readLine());

br.close();

socket.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

In this section, we have mastered the single communication of Socket, so how to realize the bidirectional communication of Socket? In the next section, we will focus on explaining the next ~

"Full Stack Java Notes" is a series of Java Engineer Notes that helps you grow from zero to one. The author is known as Mr. G in Jianghu. He has 10 years of Java R & D experience. He was engaged in software design and R & D work in a R & D center of Digital China and Aerospace Academy. He gradually became an engineer, senior engineer and architect from Xiaobai. Proficient in Java platform software development, proficient in JAVAEE, familiar with various popular development frameworks.

The notes consist of six major sections from shallow to deep:

A-Java Getting Started

B-Database from beginner to master

C-Edge Mobile Front and Web Front

D-J2EE from understanding to actual combat

E-Java Advanced Framework

F-Linux and Hadoop

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report