UDP transmission: Set up a simple chat room... set up a udp chat room ..

Source: Internet
Author: User

UDP transmission: Set up a simple chat room... set up a udp chat room ..

Reprinted please indicate the source, thank you: http://blog.csdn.net/harryweasley/article/details/45665309

I recently read a teaching video and learned socket programming. There is an example in which I feel that it is well written. I will organize it here to help me recall and view it.


Write a chat program.
It contains the part of the received data and the part of the sent data.
These two parts must be executed simultaneously.
The multithreading technology is required.
One thread controls receiving and one thread controls sending.


Because the receiving and sending actions are inconsistent, we need to define two run methods.
The two methods must be encapsulated into different classes.


Effect:


Because I only have one PC, only my own 192.168.1.48 can be used to send data ~~~ Sorry...

About dos window, run java, you can read this article http://blog.csdn.net/harryweasley/article/details/45559129

/* Write a chat program. It contains the part of the received data and the part of the sent data. These two parts must be executed simultaneously. The multithreading technology is required. One thread controls receiving and one thread controls sending. Because the receiving and sending actions are inconsistent, we need to define two run methods. The two methods must be encapsulated into different classes. */Import java. io. *; import java.net. *;/* defines a udp sender. Idea: 1. Establish the updsocket service. 2. provide data and encapsulate the data into data packets. 3. Send data packets through the sending function of the socket service. 4. Close the resource. */Class Send implements Runnable {private DatagramSocket ds; public Send (DatagramSocket ds) {this. ds = ds;} public void run () {try {BufferedReader bufr = new BufferedReader (new InputStreamReader (System. in); String line = null; while (line = bufr. readLine ())! = Null) {byte [] buf = line. getBytes (); // determine the data and encapsulate it into a data packet. DatagramPacket (byte [] buf, int length, // InetAddress address, int port) DatagramPacket dp = new DatagramPacket (buf, buf. length, InetAddress. getByName ("192.168.1.255"), 10002); // send existing data packets through the socket service. Use the send method. Ds. send (dp); if ("886 ". equals (line) break;} catch (Exception e) {throw new RuntimeException ("sending end failed") ;}}/*** defines the udp receiving end. * Idea: 1. Define the udpsocket service. Usually listen to a port. In fact, it is to define a digital ID for the receiving network application. * It is convenient to identify which data can be processed by the application. ** 2. Define a data packet because the received bytes are to be stored. Because the data packet object has more functions to extract different data information from the byte data. * 3. Use the receive method of the socket service to store the received data into the predefined data packet. 4. Special Functions of the data packet object. Extract the different data. Print it on the console. * 5. Close the resource. */Class Rece implements Runnable {private DatagramSocket ds; public Rece (DatagramSocket ds) {this. ds = ds;} public void run () {try {while (true) {// defines the data packet. Used to store data. Byte [] buf = new byte [1024]; DatagramPacket dp = new DatagramPacket (buf, buf. length); // store the received data into the data packet through the receive method of the service. Blocking method ds. receive (dp); // obtain the data through the data packet method. String ip = dp. getAddress (). getHostAddress (); String data = new String (dp. getData (), 0, dp. getLength (); 'if ("886 ". equals (data) {System. out. println (ip + ".... leave the chat room "); break;} System. out. println (ip + ":" + data) ;}} catch (Exception e) {throw new RuntimeException ("acceptor failed ");}}} class ChatDemo {public static void main (String [] args) throws Exception {DatagramSocket sendSocket = new DatagramSocket (); // create udp Socket. DatagramSocket receSocket = new DatagramSocket (10002); new Thread (new Send (sendSocket). start (); new Thread (new Rece (receSocket). start ();}}

Note: InetAddress. getByName ("192.168.1.255") indicates receiving information of the entire LAN, which is a broadcast address.

For TCP transmission, you can view this article TCP transmission: Use the socket service to implement a Text Converter.

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.