Examples of java TCP-based Network Communication

Source: Internet
Author: User

In JAVA, two network programming modes are designed: TCP and UDP. TCP is instant communication, and UDP is communication through data packets, UDP involves data parsing and transmission. In terms of security performance, TCP is superior, and data loss is not easy during communication. If one party is interrupted, the communication between the two Parties will end. During UDP packet transmission, one Party is interrupted, data packets may be lost, and the order of incoming data packets may be disordered. In terms of efficiency, UDP is faster than TCP, not just a little problem, if the terminal has a function for parsing data, data packets are continuously transmitted and fed back.
The above are my own understandings. The following are two types of TCP communication;
Server class:
Copy codeThe Code is as follows: package TCP;
Import java. io .*;
Import java.net .*;
Import javax. swing .*;
Public class Server {
// Input stream on the server
Static BufferedReader br;
// Server-side output stream
Static PrintStream ps;
// Server-related interface components
Static JTextArea text;
JFrame;

Public Server (){
// Instantiation of the server interface
JFrame frame = new JFrame ("server side ");
Text = new JTextArea ();
JScrollPane scroll = new JScrollPane (text );
Frame. add (scroll );
Frame. setVisible (true );
Frame. setSize (300,400 );
// The text box on the server side cannot be edited.
Text. setEditable (false );
}

Public static void main (String [] args) throws Exception {
New Server (); // generate the Server interface
// Instantiate a server port through the server-side constructor ServerSocket (port)
ServerSocket server = new ServerSocket (2000 );
Text. append ("Listening to port 2000" + "\ n ");
// Instantiate an object that accepts server data
Socket client = server. accept ();
Br = new BufferedReader (new InputStreamReader (client. getInputStream ()));
Ps = new PrintStream (client. getOutputStream ());
String msg;
// If the input stream is not empty, print the received information to the corresponding text box and return the collected information.
While (msg = br. readLine ())! = Null)
{
Text. append ("received by the server:" + msg + "\ n ");
Ps. println (msg );
If (msg. equals ("quit "))
{
Text. append ("client" 2000 "has exited! "+" \ N ");
Text. append ("the server program will exit! ");
Break;
}
}
Ps. close ();
Br. close ();
Client. close ();
}
}

Client class:
Copy codeThe Code is as follows: package TCP;
Import java. awt .*;
Import java. awt. event .*;
Import java. io .*;
Import javax. swing .*;
Import java.net .*;
Public class Client implements ActionListener {
// There are two graphical interfaces: A connected frame and frame 1.
Private JFrame;
Private JLabel adress;
Private JLabel port;
JTextField adresstext;
JTextField porttext;
JButton connect;

Private JFrame frame1;
Private JLabel shuru;
Private JPanel panel1;
Private JPanel panel2;
Private JLabel jieshou;
JButton send;
Static JTextArea shurukuang;
Static TextArea jieshoukuang;

// Data streams received from the server
Static BufferedReader br1;
// Data stream output from the client
Static PrintStream ps;
// Data streams received from the input box on the Communication Interface
Static BufferedReader br2;
Static Socket client;
// Convert the input box string to the input stream of the string required by the string stream
Static ByteArrayInputStream stringInputStream;

Public Client (){
// Instantiate the connection interface
Frame = new JFrame ();
Adress = new JLabel ("IP address ");
Port = new JLabel ("port number ");
Adresstext = new JTextField ("127.0.0.1", 10 );
Porttext = new JTextField ("2000", 10 );
Connect = new JButton ("connection ");
// Layout of the connection interface
Frame. setLayout (new FlowLayout ());
Frame. add (adress );
Frame. add (adresstext );
Frame. add (port );
Frame. add (porttext );
Frame. add (connect );
Frame. setVisible (true );
Frame. setSize (200,150 );
Connect. addActionListener (this );
// Communication Interface instantiation
Frame1 = new JFrame ();
Shuru = new JLabel ("enter ");
Shurukuang = new JTextArea ("Please input...", 5, 40 );

Panel1 = new JPanel ();
Panel1.add (shuru );
Panel1.add (shurukuang );
Panel1.setLayout (new FlowLayout ());

Send = new JButton ("send ");
Panel2 = new JPanel ();
Jieshou = new JLabel ("accepted ");

Jieshoukuang = new TextArea (8, 60 );
Jieshoukuang. setEditable (false );

Panel2.add (jieshou );
Panel2.add (jieshoukuang );
Panel2.setLayout (new FlowLayout ());
Frame1.setLayout (new FlowLayout ());
// Communication Interface Layout
Frame1.add (BorderLayout. NORTH, panel1 );
Frame1.add (send );
Frame1.add (BorderLayout. SOUTH, panel2 );
// The communication interface is invisible during connection
Frame1.setVisible (false );
Frame1.setSize (500,350 );
Send. addActionListener (this );
}
// Both interfaces have corresponding button time to add actions for the corresponding time
Public void actionreceivmed (ActionEvent e ){
If (e. getSource () = connect ){
Try {
// Instantiate a client when the connection button is triggered
Client = new Socket ("127.0.0.1", 2000 );
// Hide the connection interface and display the communication interface
Frame. setVisible (false );
Frame1.setVisible (true );
Jieshoukuang. append ("already connected to the server! "+" \ N ");
} Catch (IOException e1 ){
System. out. println ("the link failed! ");
E1.printStackTrace ();
}
}
// Send button corresponding time processing on the Communication Interface
If (e. getSource () = send ){
// Convert the string in the input box to a string stream
StringInputStream = new ByteArrayInputStream (shurukuang. getText (). getBytes ());
Br2 = new BufferedReader (new InputStreamReader (stringInputStream ));
String msg;
Try {
While (msg = br2.readLine ())! = Null ){
Ps. println (msg); // send the content in the input box to the server
Jieshoukuang. append ("send to server:" + msg + "\ n ");
Jieshoukuang. append ("the client accepts the following:" + br1.readLine () + "\ n ");
If (msg. equals ("quit "))
{
Jieshoukuang. append ("the client will quit! ");
Br1.close ();
Ps. close ();
Client. close ();
Frame1.setVisible (false );
Break;
}
}
} Catch (IOException e2 ){
System. out. println ("An error occurred while reading the data in the input box! ");
}
Shurukuang. setText ("");
}
}

Public static void main (String [] args) throws IOException {
New Client (); // instantiate the connection interface
Client = new Socket ("127.0.0.1", 2000 );
// Data received from the server
Br1 = new BufferedReader (new InputStreamReader (client. getInputStream ()));
// Data output from the client
Ps = new PrintStream (client. getOutputStream ());
}
}

There are several problems after writing these two classes:
1) Why does the main function need to be modified using static?
2) Why can't the buffer object BufferedReader be directly used for judgment? Do you have to assign the read data to the string for operations?
3) In the Connect button event on the connection interface, I instantiate a client object, but I comment out client = new Socket ("127.0.0.1", 2000) in the main function ); the NULLPOINTEXCEPTION exception will be thrown. I don't understand it?
I hope that the experts who have read this article can give me some advice, and I am constantly turning Think in java, hoping to find my answer in an inconspicuous corner.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.