Teach you Socket communication (TCP/IP) step by step

Teach you Socket communication (TCP/IP) step by step

Two programs on the network exchange data through a two-way communication connection, one end of which is called a socket.

To establish a network communication connection, at least a pair of port numbers (sockets) are required. The essence of sockets is a programming interface (API), which is the encapsulation of TCP/IP. TCP/IP also provides an interface for programmers to use for network development, which is the Socket programming interface; HTTP is a car, which provides a specific form of encapsulation or display of data; Socket is an engine, which provides the ability of network communication.

Download Eclipse:

https://www.eclipse.org/

This article will give a complete Socket communication code, which is tested and effective in eclipse. It is the same to develop with Java in Android Studio, just match the code with the control and register the listener. The difference is that the import declaration in AS is different, and the window does not need to be created by yourself.

The effect is as shown below:

In eclipse, File → New → Java Project → give it an English name → Finish (I named it TCP)

Directory structure:

After the new package is created, there is a src default package. Right-click src → New → Package → enter com.net (because the name of the package I use in the program is this, you can change both at the same time) → Finish

Then right-click com.net → New → Class → enter TCPClient (because this is the class name I use in my program)

Then right-click com.net → New → Class → enter TCPServer (because this is the class name I use in my program)

Paste the code in each of them:

TCPServer

  1. package com.net;
  2.  
  3. import java.io.*;
  4. import java.net.*;
  5. import java.awt.*;
  6. import java.awt.event.*;
  7.  
  8. public class TCPServer {
  9. static DataInputStream dis= null ;
  10. public   static void main(String[] args){
  11. boolean started = false ;
  12. Socket s = null ;
  13. TextArea ta = new TextArea();
  14. ta.append( "Data received from the client: " + "\n" );
  15. ServerSocket ss = null ;
  16. try{
  17. ss=new ServerSocket(8866); //Port number
  18. }catch(BindException e){
  19. System.exit(0);
  20. }catch(IOException e){
  21. e.printStackTrace();
  22. }
  23. Frame f=new Frame( "Server side" ); //Form name
  24. f.setLocation(300, 300); //Window appearance position
  25. f.setSize(200, 200); //Window size
  26. f. add (ta,BorderLayout.NORTH);
  27. f.pack();
  28. f.addWindowListener(new WindowAdapter(){
  29. public void windowClosing(WindowEvent e){
  30. System.exit(0);
  31. }
  32. });
  33. f.setVisible( true );
  34. try{ //try-catch block catches exceptions
  35. started = true ;
  36. while(started){
  37. boolean bConnected= false ;
  38. s=ss.accept();
  39. bConnected = true ;
  40. dis=new DataInputStream(s.getInputStream());
  41. while(bConnected){
  42. String str=dis.readUTF();
  43. ta.append(str+ "\n" );
  44. }
  45. }
  46. }catch(EOFException e){
  47. System. out .println( "Client closed!" );
  48. }catch(IOException e){
  49. e.printStackTrace();
  50. }finally{
  51. try{
  52. if (dis!= null )
  53. dis.close ();
  54. if(s!= null )
  55. s.close ();
  56. }catch(Exception e){
  57. e.printStackTrace();
  58. }
  59. }
  60. }
  61. }

TCPClient

  1. package com.net;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import java.io.*;
  5. import java.net.*;
  6.  
  7. public class TCPClient extends Frame{
  8. Socket s = null ;
  9. DataOutputStream dos = null ;
  10. DataInputStream dis = null ;
  11. TextField tf=new TextField(40);
  12. List list = new List(6);
  13. public   static void main(String[] args){
  14. TCPClient client=new TCPClient();
  15. client.list.add ( "Data sent to the server:" );
  16. client.setTitle( "Client" );
  17. client.run();
  18. }
  19. public void run(){
  20. setLocation(400,300);
  21. this.setSize(300, 300);
  22. add (tf,BorderLayout.SOUTH);
  23. add (list,BorderLayout.NORTH);
  24. pack();
  25. this.addWindowListener(new WindowAdapter(){
  26. public void windowClosing(WindowEvent e){
  27. disconnect();
  28. System.exit(0);
  29. }
  30. });
  31. tf.addActionListener(new MyListener());
  32. setVisible( true );
  33. connect ();
  34. }
  35. public void connect () {
  36. try{
  37. s=new Socket( "127.0.0.1" ,8866);
  38. dos=new DataOutputStream(s.getOutputStream());
  39. }catch(UnknownHostException e){
  40. e.printStackTrace();
  41. }catch(IOException e){
  42. e.printStackTrace();
  43. }
  44. }
  45. public void disconnect(){
  46. try{
  47. dos.close ();
  48. s.close ();
  49. }catch(IOException e){
  50. e.printStackTrace();
  51. }
  52. }
  53. private class MyListener implements ActionListener{
  54. public void actionPerformed(ActionEvent e){
  55. String s1 = null ;
  56. String s2 = null ;
  57. String str=tf.getText().trim();
  58. list.add (str);
  59. tf.setText( "" );
  60. try{
  61. dos.writeUTF(str);
  62. dos.flush();
  63. }catch(IOException e1){
  64. e1.printStackTrace();
  65. }
  66. }
  67. }
  68. }

Then run the server first, then run the client, otherwise an error will be reported, because the essence of Socket communication is to open the server listening port first. Then the effect diagram will appear.

The local loopback IP is 127.0.0.1. You can change it to other IP addresses to achieve cross-machine Socket communication.

This article is reprinted from the WeChat public account "Embedded Linux System Development". You can follow it through the following QR code. To reprint this article, please contact the WeChat public account of Embedded Linux System Development.

<<:  Slow SQL Management Sharing

>>:  Weibu Online was shortlisted for CDM 2021 Black Unicorn Awards

Recommend

What does the request data packet go through from sending to receiving?

Previously, we talked about how the domain name i...

Hostodo: $34.99/year KVM-2.5GB/25G NVMe/8TB/3 data centers

Hostodo released two special packages in Septembe...

A quick overview of 5G industry developments in May 2021

After the rapid development in 2020, 2021 is a cr...

Knowledge points of wireless network coverage system

1. What is AP? Answer: AP - Wireless Access Point...