A case study on Java TCP network communication _java

Source: Internet
Author: User
Tags readline server port
Java Design Network Programming mode is mainly TCP and UDP two kinds, TCP is an instant communication, UDP is through the packet to communicate, UDP will be involved in the data analysis and transmission. In the security performance aspect, TCP wants to slightly, the communication process is not easy to appear the phenomenon which the data loses, one side of the interruption, the two sides of the communication will end, the process of UDP packet transmission, one interruption, data packets are very likely to be lost, there are also possible packets of the order of the disorder; in terms of efficiency, UDP faster than TCP is not just a little bit of a problem, if the terminal has the function of parsing data method, the packet will be continuously transmitted over, and then feedback back.
The above is my own understanding, the following is about the TCP protocol communication two classes;
Server class:
Copy Code code as follows:

Package TCP;
Import java.io.*;
Import java.net.*;
Import javax.swing.*;
public class Server {
Server-Side input stream
Static BufferedReader BR;
Server-Side output stream
Static PrintStream PS;
Server-related interface components
static JTextArea text;
JFrame frame;

Public Server () {
Instantiation of the server-side 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);
This sets the server-side text boxes that are not editable
Text.seteditable (FALSE);
}

public static void Main (string[] args) throws exception{
New Server (); Build Server Interface
Instantiate a server port via server-side constructor ServerSocket (port)
ServerSocket server=new ServerSocket (2000);
Text.append ("Monitor 2000 port" + "\ 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 appropriate text box and feedback the information that is collected
while ((msg =br.readline ())!=null)
{
Text.append ("Server Side Received:" +msg+ "\ n");
PS.PRINTLN (msg);
if (Msg.equals ("Quit"))
{
Text.append ("Client" 2000 has exited!) "+" \ n ");
Text.append ("server program will exit!") ");
Break
}
}
Ps.close ();
Br.close ();
Client.close ();
}
}

Client class:
Copy Code code 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{
Here are two graphical interfaces, one is the frame of the connection, and the other is the interface of the server communication frame1
Private JFrame frame;
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 accepted from the server
Static BufferedReader BR1;
Data flow from client output
Static PrintStream PS;
Data stream accepted from the input box in the communication interface
Static BufferedReader Br2;
static Socket client;
The input stream that converts the input box string to the string required by the string stream
Static Bytearrayinputstream Stringinputstream;

Public Client () {
The instantiation of 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);
The instantiation of communication interface
Frame1=new JFrame ();
Shuru=new JLabel ("Please 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 ());
The layout of the communication interface
Frame1.add (BORDERLAYOUT.NORTH,PANEL1);
Frame1.add (send);
Frame1.add (BORDERLAYOUT.SOUTH,PANEL2);
The communication interface is not visible at the time of the connection
Frame1.setvisible (FALSE);
Frame1.setsize (500,350);
Send.addactionlistener (this);
}
Two interfaces have the corresponding button time, add action for the corresponding time
public void actionperformed (ActionEvent e) {
if (E.getsource () ==connect) {
try {
Instantiating a client when the connection button is triggered
Client=new Socket ("127.0.0.1", 2000);
Hide connection interface, display communication interface
Frame.setvisible (FALSE);
Frame1.setvisible (TRUE);
Jieshoukuang.append ("Already connected to the server!") "+" \ n ");
catch (IOException E1) {
System.out.println ("link failed!") ");
E1.printstacktrace ();
}
}
The corresponding time processing of the Send button in the communication interface
if (E.getsource () ==send) {
Converts a string in an 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 contents of the input box to the server side
Jieshoukuang.append ("Send to Server:" +msg+ "\ n");
Jieshoukuang.append ("Client accepts accordingly:" +br1.readline () + "\ n");
if (Msg.equals ("Quit"))
{
Jieshoukuang.append ("Client will exit!");
Br1.close ();
Ps.close ();
Client.close ();
Frame1.setvisible (FALSE);
Break
}
}
}catch (IOException E2) {
SYSTEM.OUT.PRINTLN ("Error reading input box data!") ");
}
Shurukuang.settext ("");
}
}

public static void Main (string[] args) throws ioexception{
New Client (); Instantiating a connection interface
Client=new Socket ("127.0.0.1", 2000);
Data accepted from the server
Br1=new BufferedReader (New InputStreamReader (Client.getinputstream ()));
Data output from the client
PS =new PrintStream (Client.getoutputstream ());
}
}

After writing these two classes, there are still a few questions:
1 Why does the main function have to be decorated with static?
2 Buffer Object BufferedReader Why not directly used to judge, do not want to read the data assigned to the string to operate?
3 in the connection interface between the Connect button event I have instantiated a client object, but I commented out the main function of the client=new Socket ("127.0.0.1", 2000); This sentence, you will find thrown nullpointexception exception, I do not understand?
Hope to see this article Daniel can not hesitate to enlighten me, I am also constantly flipping through the "Look in Java" hope to find in some obscure corner of my answer.
Related Article

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.