Java UDP Simple Chat program instance code _java

Source: Internet
Author: User
Tags gettext stub trim lenovo

Learned computer network communications are aware that the transfer of data between computers by two kinds, that is, TCP communication and UDP communication. TCP is a reliable connection-oriented communication protocol, and two UDP is unreliable for connectionless communication protocols.

In Java, there is TCP based network socket communication, but also UDP based User datagram communication, UDP information transmission speed, but unreliable!

Basic mode based on UDP communication:

(1) Package The data, called a packet (like putting a letter into an envelope), and then send the packet to the destination.

(2) Accept packets from others (like receiving envelopes), and then view the contents of the packet.

Client

Copy Code code as follows:

Package Com.client.view;

Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import Java.awt.event.WindowAdapter;
Import java.awt.event.WindowEvent;
Import Java.io.ObjectOutputStream;

Import Javax.swing.ImageIcon;
Import Javax.swing.JButton;
Import Javax.swing.JFrame;
Import Javax.swing.JOptionPane;
Import Javax.swing.JPanel;
Import Javax.swing.JTextArea;
Import Javax.swing.JTextField;

Import Com.tools.ClientToServerThread;

/**
* @author Lenovo
*
*/
public class Jchatfrm extends JFrame implements actionlistener{


JTextArea JTA;
JTextField JTF;
JButton JB;
JPanel JP;
String ownerID;
String friendID;

Clienttoserverthread CtsT;
public static void Main (string[] args) {
TODO auto-generated Method Stub
New Jchatfrm ();
}

Public Jchatfrm ()
{
Settitle ("Client");
Jta=new JTextArea ();
Jtf=new JTextField (15);
Jb=new JButton ("send");
Jb.addactionlistener (this);
Jp=new JPanel ();
Jp.add (JTF);
Jp.add (JB);

This.add (JTA, "Center");
This.add (JP, "South");
This.settitle (ownerid+ "chatting" with "+friend+");
This.seticonimage (New ImageIcon ("Image/qq.gif"). GetImage ());
This.setsize (300, 200);
This.setbounds (300, 200, 300, 200);
This.setvisible (TRUE);
Setdefaultcloseoperation (Jframe.dispose_on_close);
CtsT = new Clienttoserverthread (JTA);
Ctst.start ();

/** Form Close button Event * *
This.addwindowlistener (New Windowadapter ()
{
public void windowclosing (WindowEvent e)
{
if (Joptionpane.showconfirmdialog (null, "{
System.exit (0);
Ctst.closesocket ();
}
Else
{
Return
}
}
}
);
}

Write a method that lets it display a message
public void ShowMessage (String message)
{
String info= message;
This.jta.append (info);
}

public void actionperformed (ActionEvent arg0) {
TODO auto-generated Method Stub
if (Arg0.getsource () ==JB)
{
byte buffer[] = Jtf.gettext (). Trim (). GetBytes ();
Ctst.senddata (buffer);
}

}
}

Copy Code code as follows:

Package com.tools;

Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.ObjectInputStream;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;
Import Java.net.Socket;
Import java.util.Properties;

Import Javax.swing.JTextArea;

Import Com.common.User;

/**
* @author Lenovo
*
*/
public class Clienttoserverthread extends thread{

Private String ServerIP = "127.0.0.1";
private int serverport = 8888;
private int receiveport = 6666;
Statement of datagram for sending information
Private Datagramsocket sendsocket = null;
Declaring packets that send information
Private Datagrampacket sendpacket = null;
Statement of datagram statements accepting information
Private Datagramsocket receivesocket = null;
Declaring a datagram that accepts information
Private Datagrampacket receivepacket = null;
Port to send and receive data
private int myport = 0;
IP address of the receiving data host
Private String Friendip = null;
private int friendport = 0;

Size of buffered array
public static final int buffer_size = 5120;

Private byte inbuf[] = null; Buffer array to receive data
Private byte outbuf[] = null; Buffer array to send data

JTextArea JTA;

Constructors
Public Clienttoserverthread (JTextArea JTA) {
This.jta = JTA;
Getpropertiesinfo ();
}

public void Run () {
String receiveinfo = "";
try{
Inbuf = new Byte[buffer_size];
Receivepacket = new Datagrampacket (inbuf,inbuf.length);
Receivesocket = new Datagramsocket (ReceivePort);
}catch (Exception e) {
E.printstacktrace ();
Todo:handle exception
}

while (true) {
if (Receivesocket = = null) {
Break
} else {
try {
Receivesocket.receive (Receivepacket);
String message = new String (Receivepacket.getdata (), 0,receivepacket.getlength ());
Jta.append ("Received data" +message+ "\ n");
catch (Exception e) {
E.printstacktrace ();
Todo:handle exception
}
}
}
}
/**
* This method is used to obtain the IP, PORT in the server properties file
*/
private void Getpropertiesinfo () {
Properties prop = new properties ();
InputStream instream = Thread.CurrentThread (). Getcontextclassloader ()
. getResourceAsStream ("serverinfo.properties");
try{
Gets the corresponding key value pair
Prop.load (instream);
}catch (IOException e) {
E.printstacktrace ();
}

Get the corresponding value according to the corresponding key
ServerIP = Prop.getproperty ("ServerIP");
ServerPort = Integer.parseint (Prop.getproperty ("Serverudp.port"));
ReceivePort = Integer.parseint (Prop.getproperty ("Receiveudp.port"));


}
public void SendData (byte buffer[]) {
try{
InetAddress address = Inetaddress.getbyname (ServerIP);
Outbuf = new Byte[buffer_size];
Sendpacket = new Datagrampacket (buffer,buffer.length,address,serverport);
Sendsocket = new Datagramsocket ();
Sendsocket.send (Sendpacket);
}catch (Exception e) {
E.printstacktrace ();
Todo:handle exception
}
}
public void Closesocket () {
Receivesocket.close ();
}
}

Server:

Copy Code code as follows:

Package Com.server.view;

Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import Java.awt.event.WindowAdapter;
Import java.awt.event.WindowEvent;
Import Java.io.ObjectOutputStream;

Import Javax.swing.ImageIcon;
Import Javax.swing.JButton;
Import Javax.swing.JFrame;
Import Javax.swing.JOptionPane;
Import Javax.swing.JPanel;
Import Javax.swing.JTextArea;
Import Javax.swing.JTextField;

Import Com.tools.ClientToServerThread;

/**
* @author Lenovo
*
*/
public class Jchatfrm extends JFrame implements actionlistener{


JTextArea JTA;
JTextField JTF;
JButton JB;
JPanel JP;
String ownerID;
String friendID;

Clienttoserverthread CtsT;
public static void Main (string[] args) {
TODO auto-generated Method Stub
New Jchatfrm ();
}

Public Jchatfrm ()
{
Settitle ("server");
Jta=new JTextArea ();
Jtf=new JTextField (15);
Jb=new JButton ("send");
Jb.addactionlistener (this);
Jp=new JPanel ();
Jp.add (JTF);
Jp.add (JB);

This.add (JTA, "Center");
This.add (JP, "South");
This.settitle (ownerid+ "chatting" with "+friend+");
This.seticonimage (New ImageIcon ("Image/qq.gif"). GetImage ());
This.setsize (300, 200);
This.setbounds (300, 200, 300, 200);
This.setvisible (TRUE);
Setdefaultcloseoperation (Jframe.dispose_on_close);
CtsT = new Clienttoserverthread (JTA);
Ctst.start ();

/** Form Close button Event * *
This.addwindowlistener (New Windowadapter ()
{
public void windowclosing (WindowEvent e)
{
if (Joptionpane.showconfirmdialog (null, "{
System.exit (0);
Ctst.closesocket ();
}
Else
{
Return
}
}
}
);
}

Write a method that lets it display a message
public void ShowMessage (String message)
{
String info= message;
This.jta.append (info);
}

public void actionperformed (ActionEvent arg0) {
TODO auto-generated Method Stub
if (Arg0.getsource () ==JB)
{
byte buffer[] = Jtf.gettext (). Trim (). GetBytes ();
Ctst.senddata (buffer);
}

}
}

Copy Code code as follows:

Package com.tools;

Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.ObjectInputStream;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;
Import Java.net.Socket;
Import java.util.Properties;

Import Javax.swing.JTextArea;

Import Com.common.User;

/**
* @author Lenovo
*
*/
public class Clienttoserverthread extends thread{

Private String Sendip = "127.0.0.1";
private int sendport = 6666;
private int receiveport = 8888;
Statement of datagram for sending information
Private Datagramsocket sendsocket = null;
Declaring packets that send information
Private Datagrampacket sendpacket = null;
Statement of datagram statements accepting information
Private Datagramsocket receivesocket = null;
Declaring a datagram that accepts information
Private Datagrampacket receivepacket = null;
Port to send and receive data
private int myport = 0;
IP address of the receiving data host
Private String Friendip = null;
private int friendport = 0;

Size of buffered array
public static final int buffer_size = 5120;

Private byte inbuf[] = null; Buffer array to receive data
Private byte outbuf[] = null; Buffer array to send data

JTextArea JTA;

Constructors
Public Clienttoserverthread (JTextArea JTA) {
This.jta = JTA;
Getpropertiesinfo ();
}

public void Run () {
String receiveinfo = "";
try{
Inbuf = new Byte[buffer_size];
Receivepacket = new Datagrampacket (inbuf,inbuf.length);
Receivesocket = new Datagramsocket (ReceivePort);
}catch (Exception e) {
E.printstacktrace ();
Todo:handle exception
}

while (true) {
if (Receivesocket = = null) {
Break
} else {
try {
Receivesocket.receive (Receivepacket);
String message = new String (Receivepacket.getdata (), 0,receivepacket.getlength ());
Jta.append ("Received data" +message+ "\ n");
catch (Exception e) {
E.printstacktrace ();
Todo:handle exception
}
}
}
}
/**
* This method is used to obtain the IP, PORT in the server properties file
*/
private void Getpropertiesinfo () {
Properties prop = new properties ();
InputStream instream = Thread.CurrentThread (). Getcontextclassloader ()
. getResourceAsStream ("serverinfo.properties");
try{
Gets the corresponding key value pair
Prop.load (instream);
}catch (IOException e) {
E.printstacktrace ();
}

Get the corresponding value according to the corresponding key

ReceivePort = Integer.parseint (Prop.getproperty ("Serverudp.port"));



}
public void SendData (byte buffer[]) {
try{
InetAddress address = Inetaddress.getbyname (SENDIP);
Outbuf = new Byte[buffer_size];
Sendpacket = new Datagrampacket (buffer,buffer.length,address,sendport);
Sendsocket = new Datagramsocket ();
Sendsocket.send (Sendpacket);
}catch (Exception e) {
E.printstacktrace ();
Todo:handle exception
}
}
public void Closesocket () {
Receivesocket.close ();
}
}

Run Screenshots:

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.