In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "how to realize the network programming function of Java based on TCP protocol". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
I. one-way communication
Function: the client sends a message to the server:
Client:
Public class TestClient {/ / client / / this is a main method, which is the entrance to the program: public static void main (String [] args) throws IOException {/ / 1. Create a socket: specify the ip and port number of the server: Socket s = new Socket ("192.168.199.217", 8888); / / 2. For programmers, sending data feels like "using the output stream: OutputStream os = s.getOutputStream (); DataOutputStream dos = new DataOutputStream (os); / / using this OutputStream, you can send data out, but there is no way to send String directly / / so we have another processing stream outside the OutputStream: DataOutputStream dos.writeUTF (" Hello "); / / 3. Close stream + close network resources: dos.close (); os.close (); s.close ();}}
Server side:
Public class TestServer {/ / server / / this is a main method, which is the entrance to the program: public static void main (String [] args) throws IOException {/ / 1. Create a socket: specify the server's port number ServerSocket ss = new ServerSocket (8888); / / 2. Waiting for a message from the client: Socket s = ss.accept (); / / blocking method: waiting to receive data from the client, when to receive the data, and when the program continues to execute downwards. The return value of / / accept () is a Socket. The Socket actually means that after the client's Socket / / receives the Socket, the client and the server have a real connection and can communicate / / 3. Feel the operation flow: InputStream is = s.getInputStream (); DataInputStream dis = new DataInputStream (is); / / 4. Read the data sent by the client: String str = dis.readUTF (); System.out.println ("the data sent by the client is:" + str); / / 5. Close streams + close network resources: dis.close (); is.close (); s.close (); ss.close ();}}
Test:
Open the client first or the server first: open the server first, and then turn on the client side verification: open the client first: error.
As shown in the figure:
II. Two-way communication
Client:
Import java.io.*;import java.net.Socket;public class TestClient {/ / client / / this is a main method, which is the entrance to the program: public static void main (String [] args) throws IOException {/ / 1. Create a socket: specify the ip and port number of the server: Socket s = new Socket ("192.168.199.217", 8888); / / 2. For programmers, sending data feels like "using the output stream: OutputStream os = s.getOutputStream (); DataOutputStream dos = new DataOutputStream (os); / / using this OutputStream, you can send data out, but there is no way to send String directly / / so we set another processing stream outside the OutputStream: DataOutputStream dos.writeUTF (" Hello "). / / receive the reply from the server-"use the input stream: InputStream is = s.getInputStream (); DataInputStream dis = new DataInputStream (is); String str = dis.readUTF (); System.out.println (" the server says to me: "+ str); / / 3. Close streams + close network resources: dis.close (); is.close (); dos.close (); os.close (); s.close ();}}
Server side:
Import java.io.*;import java.net.ServerSocket;import java.net.Socket;public class TestServer {/ / server / / this is a main method, which is the entrance to the program: public static void main (String [] args) throws IOException {/ / 1. Create a socket: specify the server's port number ServerSocket ss = new ServerSocket (8888); / / 2. Waiting for a message from the client: Socket s = ss.accept (); / / blocking method: waiting to receive data from the client, when to receive the data, and when the program continues to execute downwards. The return value of / / accept () is a Socket. The Socket actually means that after the client's Socket / / receives the Socket, the client and the server have a real connection and can communicate / / 3. Feel the operation flow: InputStream is = s.getInputStream (); DataInputStream dis = new DataInputStream (is); / / 4. Read the data sent by the client: String str = dis.readUTF (); System.out.println ("the data sent by the client is:" + str); / / output a sentence to the client:-"Operation stream -" output stream OutputStream os = s.getOutputStream (); DataOutputStream dos = new DataOutputStream (os) Dos.writeUTF ("Hello, I am the server, I received your request"); / / 5. Close streams + close network resources: dos.close (); os.close (); dis.close (); is.close (); s.close (); ss.close ();}}
Note: turn off the firewall
III. Object stream transmission
Encapsulated User class:
Import java.io.Serializable;public class User implements Serializable {private static final long serialVersionUID = 9050691344308365540L; private String name; private String pwd; public String getName () {return name;} public void setName (String name) {this.name = name;} public String getPwd () {return pwd;} public void setPwd (String pwd) {this.pwd = pwd } public User (String name, String pwd) {this.name = name; this.pwd = pwd;}}
Client:
Import java.io.*;import java.net.Socket;import java.util.Scanner;public class TestClient {/ / client / / this is a main method, which is the entrance to the program: public static void main (String [] args) throws IOException {/ / 1. Create socket: specify the ip and port number of the server: Socket s = new Socket ("192.168.199.217", 8888); / / enter the user's account number and password: Scanner sc = new Scanner (System.in); System.out.println ("Please enter your account:"); String name = sc.next (); System.out.println ("Please enter your password:") String pwd = sc.next (); / / encapsulate the account and password as a User object: User user = new User (name,pwd); / / 2. For programmers, send data feelings out-- "using the output stream: OutputStream os = s.getOutputStream (); ObjectOutputStream oos = new ObjectOutputStream (os); oos.writeObject (user); / / receiving a reply from the server--" using the input stream: InputStream is = s.getInputStream (); DataInputStream dis = new DataInputStream (is); boolean b = dis.readBoolean () If (b) {System.out.println ("Congratulations, login success");} else {System.out.println ("sorry, login failed");} / / 3. Close streams + close network resources: dis.close (); is.close (); oos.close (); os.close (); s.close ();}}
Server:
Import java.io.*;import java.net.ServerSocket;import java.net.Socket;public class TestServer {/ / server / / this is a main method, which is the entrance to the program: public static void main (String [] args) throws IOException, ClassNotFoundException {/ / 1. Create a socket: specify the server's port number ServerSocket ss = new ServerSocket (8888); / / 2. Waiting for a message from the client: Socket s = ss.accept (); / / blocking method: waiting to receive data from the client, when to receive the data, and when the program continues to execute downwards. The return value of / / accept () is a Socket. The Socket actually means that after the client's Socket / / receives the Socket, the client and the server have a real connection and can communicate / / 3. Feel the operation flow: InputStream is = s.getInputStream (); ObjectInputStream ois = new ObjectInputStream (is); / / 4. Read the data sent by the client: User user = (User) (ois.readObject ()); / / verify a pair of objects: boolean flag = false; if (user.getName (). Equals ("Nana") & & user.getPwd (). Equals ("123123")) {flag = true } / / output result to client:-"Operation flow -" output stream OutputStream os = s.getOutputStream (); DataOutputStream dos = new DataOutputStream (os); dos.writeBoolean (flag); / / 5. Close streams + close network resources: dos.close (); os.close (); ois.close (); is.close (); s.close (); ss.close ();}} IV. Add a complete way to handle exceptions
Server side:
Import java.io.*;import java.net.ServerSocket;import java.net.Socket;public class TestServer {/ / server / / this is a main method, which is the entrance to the program: public static void main (String [] args) {/ / 1. Create a socket: specify the port number of the server ServerSocket ss = null; Socket s = null; InputStream is = null; ObjectInputStream ois = null; OutputStream os = null; DataOutputStream dos = null; try {ss = new ServerSocket (8888); / / 2. Waiting for a message from the client: s = ss.accept (); / / blocking method: waiting to receive data from the client, when to receive the data, and when the program continues to execute downwards. The return value of / / accept () is a Socket. The Socket actually means that after the client's Socket / / receives the Socket, the client and the server have a real connection and can communicate / / 3. Feel the operation flow: is = s.getInputStream (); ois = new ObjectInputStream (is); / / 4. Read the data sent by the client: User user = (User) (ois.readObject ()); / / verify a pair of objects: boolean flag = false; if (user.getName (). Equals ("Nana") & & user.getPwd (). Equals ("123123")) {flag = true Output result to client:-"Operation flow -" output stream os = s.getOutputStream (); dos = new DataOutputStream (os); dos.writeBoolean (flag);} catch (IOException | ClassNotFoundException e) {e.printStackTrace ();} finally {/ / 5. Close the stream + close the network resources: try {if (dosages null) {dos.close ();}} catch (IOException e) {e.printStackTrace () } try {if (ossified null) {os.close ();}} catch (IOException e) {e.printStackTrace ();} try {if (oispanic null) {ois.close () }} catch (IOException e) {e.printStackTrace ();} try {if (isometric null) {is.close ();}} catch (IOException e) {e.printStackTrace () } try {if (slotted null) {s.close ();}} catch (IOException e) {e.printStackTrace ();} try {if (essentially null) {ss.close () } catch (IOException e) {e.printStackTrace ();}}
Client:
Import java.io.*;import java.net.Socket;import java.util.Scanner;public class TestClient {/ / client / / this is a main method, which is the entrance to the program: public static void main (String [] args) {/ / 1. Create socket: specify the ip and port number of the server: Socket s = null; OutputStream os = null; ObjectOutputStream oos = null; InputStream is = null; DataInputStream dis = null; try {s = new Socket ("192.168.199.217", 8888); / enter the user's account number and password: Scanner sc = new Scanner (System.in) System.out.println ("Please enter your account:"); String name = sc.next (); System.out.println ("Please enter your password:"); String pwd = sc.next (); / / encapsulate the account and password as a User object: User user = new User (name,pwd); / / 2. For programmers, send data feelings out-- "using the output stream: os = s.getOutputStream (); oos = new ObjectOutputStream (os); oos.writeObject (user); / / receiving a reply from the server--" using the input stream: is = s.getInputStream (); dis = new DataInputStream (is) Boolean b = dis.readBoolean (); if (b) {System.out.println ("Congratulations on login success");} else {System.out.println ("sorry, login failed");} catch (IOException e) {e.printStackTrace () } finally {/ / 3. Close the stream + close the network resources: try {if (disconnected null) {dis.close ();}} catch (IOException e) {e.printStackTrace () } try {if (isometric null) {is.close ();}} catch (IOException e) {e.printStackTrace ();} try {if (oosculation null) {oos.close () }} catch (IOException e) {e.printStackTrace ();} try {if (ossified null) {os.close ();}} catch (IOException e) {e.printStackTrace () } try {if (slotted null) {s.close ();}} catch (IOException e) {e.printStackTrace ();} V. Multithreading receives user requests
Question:
The server serves a request, and then the server shuts down (the program ends naturally).
Needs to be addressed:
The server must be listening and open all the time, waiting for a request from the client
In the current code, the client does not have to move
Change the server code:
Server thread:
Import java.io.*;import java.net.Socket;public class ServerThread extends Thread {/ thread: specializes in handling client requests InputStream is = null; ObjectInputStream ois = null; OutputStream os = null; DataOutputStream dos = null; Socket s = null; public ServerThread (Socket s) {this.s = s;} @ Override public void run () {try {/ / 2. Waiting for a message from the client: is = s.getInputStream (); ois = new ObjectInputStream (is); / / 4. Read the data sent by the client: User user = (User) (ois.readObject ()); / / verify a pair of objects: boolean flag = false; if (user.getName (). Equals ("Nana") & & user.getPwd (). Equals ("123123")) {flag = true } / / output result to the client:-"Operation stream -" output stream os = s.getOutputStream (); dos = new DataOutputStream (os); dos.writeBoolean (flag);} catch (IOException | ClassNotFoundException e) {e.printStackTrace () } finally {try {if (dosages null) {dos.close ();}} catch (IOException e) {e.printStackTrace ();} try {if (dosages null) {os.close () }} catch (IOException e) {e.printStackTrace ();} try {if (oispanic null) {ois.close ();}} catch (IOException e) {e.printStackTrace () } try {if (isometric null) {is.close ();}} catch (IOException e) {e.printStackTrace ();}
Server side:
Import java.io.*;import java.net.ServerSocket;import java.net.Socket;public class TestServer {/ / Server / / this is a main method that is the entry to the program: public static void main (String [] args) {System.out.println ("Server started"); / / 1. Create a socket: specify the port number of the server ServerSocket ss = null; Socket s = null; int count = 0 role / define a counter to count client requests try {ss = new ServerSocket (8888) While (true) {/ / join the endless loop, the server has been listening to whether the client sends data s = ss.accept (); / / blocking method: waiting to receive data from the client, when to receive the data, and when the program continues to execute downwards. / / each request from the client is processed by thread: new ServerThread (s). Start (); count++; / / enter the information of the requested client: System.out.println ("currently the" + count+ "user accesses our server, and the corresponding user is:" + s.getInetAddress ()). }} catch (IOException e) {e.printStackTrace ();} "how to realize the network programming function of Java based on TCP protocol" is introduced here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.