Java Series Lecture Two: Socket network communication Implementation Chat software project explanation (UDP)

Source: Internet
Author: User
Tags gettext

Last one we talked about the implementation of the network communication software development through TCP, ideas and implementation, today talk to you about the UDP communication in the socket of the software development steps and the main code, the implementation of the UDP implementation of the communication software features are not divided between the client and the server side, A program is both client and server side, the typical software is some local area network chat software, flying pigeons and other software.

UDP communication is mainly used in the java.net package of 3 classes are Datagrampacket class, Datagramsocket class and InetAddress class, the following through the implementation of a simple Chat Software small projects to explain how they are used, the code is as follows:

Package T16;


Import Java.awt.BorderLayout;

Import Java.awt.Color;

Import Java.awt.FlowLayout;

Import Java.awt.GridLayout;

Import java.awt.event.ActionEvent;

Import Java.awt.event.ActionListener;

Import java.io.IOException;

Import Java.net.DatagramPacket;

Import Java.net.DatagramSocket;

Import java.net.InetAddress;

Import java.net.SocketException;

Import java.net.UnknownHostException;

Import Java.util.Date;


Import Javax.swing.BorderFactory;

Import Javax.swing.JButton;

Import Javax.swing.JEditorPane;

Import Javax.swing.JFrame;

Import Javax.swing.JLabel;

Import Javax.swing.JOptionPane;

Import Javax.swing.JPanel;

Import Javax.swing.JTextField;

/**

* Chat software for UDP communication

*

* */

public class Udpchat extends JFrame implements actionlistener{


Private JLabel Lblport,lbladdr,lblport2;

Private JTextField Txtport,txtaddr,txtport2;

Private JButton Btnconn,btnsend,btnclose;

Private JEditorPane txtreceive,txtsend;

public udpchat (int n) {

}

Private udpchat (int n,int m) {

}

Public Udpchat () {

Super ("Chat software for UDP communication");

Lblport = new JLabel ("Native port:", jlabel.right);

LblPort2 = new JLabel ("Opposite Port:", jlabel.right);

LBLADDR = new JLabel ("Opposite address:", jlabel.right);

Txtport = new JTextField ("8888", 5);

TxtPort2 = new JTextField ("9999", 5);

InetAddress ipaddr =null;

try {

IPAddr = Inetaddress.getlocalhost ();

} catch (Unknownhostexception e) {

E.printstacktrace ();

}

TXTADDR = new JTextField (ipaddr.gethostaddress (), 10);

Btnconn = new JButton ("Connection (C))");

Btnconn.setmnemonic (' C ');

JPanel Toppanel = new JPanel (new FlowLayout (Flowlayout.left));

Toppanel.add (Lblport);

Toppanel.add (Txtport);

Toppanel.add (LBLADDR);

Toppanel.add (TXTADDR);

Toppanel.add (LBLPORT2);

Toppanel.add (TXTPORT2);

Toppanel.add (Btnconn);

txtreceive = new JEditorPane ();

Txtsend = new JEditorPane ();

JPanel Centerpanel = new JPanel (new GridLayout (2,1,5,10));

Centerpanel.add (txtreceive);

Txtreceive.setborder (Borderfactory.createloweredbevelborder ());

Receive box cannot be edited

Txtreceive.seteditable (FALSE);

Txtsend.setborder (Borderfactory.createloweredbevelborder ());

Centerpanel.add (Txtsend);

Btnsend = new JButton ("Send (S)");

Btnsend.setmnemonic (' S ');

Btnclose = new JButton ("Exit (X)");

Btnclose.setmnemonic (' X ');

JPanel Bottompanel = new JPanel (new FlowLayout (flowlayout.right));

Bottompanel.add (Btnsend);

Bottompanel.add (btnclose);

Add (Toppanel,borderlayout.north);

Centerpanel.setbackground (color.red);

Add (Centerpanel,borderlayout.center);

Add (Bottompanel,borderlayout.south);

Btnconn.addactionlistener (this);

Btnsend.addactionlistener (this);

Btnclose.addactionlistener (this);

Send button disabled

Btnsend.setenabled (FALSE);

SetSize (600, 400);

SetVisible (TRUE);

Setlocationrelativeto (NULL);

Setdefaultcloseoperation (Jframe.exit_on_close);

}


Create an inner class that implements the receive thread

Class Receivethread extends thread{

Datagramsocket socket;

Public Receivethread () {

try{

int port = integer.parseint (Txtport.gettext (). Trim ());

Socket = new Datagramsocket (port);

}catch (Exception e) {

E.printstacktrace ();

}

}

@Override

public void Run () {

Byte[] B = new byte[1024];

Datagrampacket packet = new Datagrampacket (b,b.length);

while (true) {

try {

Receive data

Socket.receive (packet);

Convert to String

String str = new String (B,0,packet.getlength ());

Show in Receive box

String content = Txtreceive.gettext ();

Content + = new Date (). toLocaleString () + "\ n";

Content + = str+ "\ n";

Txtreceive.settext (content);

} catch (IOException e) {

E.printstacktrace ();

}

}

}

}

public static void Main (string[] args) {

udpchat chat = new Udpchat ();

try {

Class.forName ("T16. Udpchat "). newinstance ();

} catch (Instantiationexception e) {

E.printstacktrace ();

} catch (Illegalaccessexception e) {

E.printstacktrace ();

} catch (ClassNotFoundException e) {

E.printstacktrace ();

}

}


@Override

public void actionperformed (ActionEvent e) {

if (E.getsource () ==btnconn) {

Btnconn.setenabled (FALSE);

Btnsend.setenabled (TRUE);

Start thread

New Receivethread (). Start ();

}else if (E.getsource () ==btnsend) {

Send content

String str = Txtsend.gettext (). Trim ();

if (Str.equals ("")) {

Joptionpane.showmessagedialog (This, "Please enter the content to be sent");

Return

}

Display the content you want to send to the Receive box

String content = Txtreceive.gettext ();

Content + = new Date (). toLocaleString () + "\ n";

Content + = str+ "\ n";

Txtreceive.settext (content);

try {

Set the offset IP address

inetaddress IP = inetaddress.getbyname (Txtaddr.gettext (). Trim ());

Set the port of each other

int port = integer.parseint (Txtport2.gettext (). Trim ());

Create a Send Package

byte b[] = Str.getbytes ();

Datagrampacket p = new Datagrampacket (b,b.length,ip,port);

Create Datagramsocket Send

Datagramsocket socket = new Datagramsocket ();

Send

Socket.send (P);

Empty the contents of the Send box

Txtsend.settext ("");

} catch (Unknownhostexception E1) {

E1.printstacktrace ();

} catch (SocketException E2) {

E2.printstacktrace ();

} catch (IOException E3) {

E3.printstacktrace ();

}

}else if (E.getsource () ==btnclose) {

System.exit (0);

}

}

}

650) this.width=650; "Src=" https://s5.51cto.com/wyfs02/M01/9B/D5/wKiom1lnhlLQwT9pAAEc0WHTlZs544.jpg-wh_500x0-wm_ 3-wmp_4-s_4008580126.jpg "title=" udp.jpg "width=", "height=" 391 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width : 700px;height:391px; "alt=" Wkiom1lnhllqwt9paaec0whtlzs544.jpg-wh_50 "/>

The program must be started with 2 instances to enable chat on the LAN, each other to set the port and IP address.

I am engaged in software project development 20, 10 Java Engineer Series of teaching work, recording more than 30 quality video courses, each course contains the project actual combat, class ppt, and complete source code download, interested friends can see my online classroom,

About the network instant messaging, multithreading and other technical details of a lot of content, if you are interested to see my java from the beginner to proficient in +QQ Instant Messaging software Project Training video , link address:/http edu.51cto.com/course/6946.html

Java Series Lecture Two: Socket network communication Implementation Chat software project explanation (UDP)

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.