C # Use UDP client to write chat programs

Source: Internet
Author: User
The udpclient class uses UDP to communicate with network services. UDP is easy to use and can broadcast messages to multiple addresses at the same time. However, because the UDP protocol is a connectionless protocol, UDP data packets sent to the remote endpoint may not arrive or necessarily in the same order of sending. Applications that use UDP must be prepared to handle Lost and incorrectly ordered data packets.

To use UDP to send data packets, you must know the network address of the network device that hosts the required service and the UDP port number that the Service uses for communication.

A special network address is used to support udp broadcast messages on an IP-based network. The following content uses the IP version 4 address family used on the Internet as an example.

IP version 4 uses a 32-bit network address. For Class C addresses that use the 255.255.255.0 network mask, these bits are divided into four eight bytes. When expressed in decimal number, these four eight-bit bytes constitute a familiar four-part notation separated by dots, such as 192.168.100.2. The first two octal bytes (192.168 in this example) constitute the network number. The third octal byte (100) defines the subnet. The last octal byte (2) is the host identifier.

Set all IP addresses to 1 (that is, broadcast bandwidth limit 255) to form a limited broadcast address. Send UDP data packets to this address to transmit messages to any host on the broadcast network. Because the router never forwards messages sent to this address, only hosts on the connected network can see these broadcasts.

By setting all the bits of some addresses to 1, you can direct the broadcast to a specific network part. For example, to send a broadcast to all hosts on the network identified by an IP address starting with 192.168, set the subnet and host part of the address to 1, for example, 192.168.255.255. To restrict the broadcast to a single subnet, set only the host part to 1, for example, 192.168.100.255.

UdpclientClass can broadcast to any network broadcast address, but it cannot listen to broadcasts sent to the network. RequiredSocketClass.

When all receivers are in a single network, or when many clients need to receive broadcasts, the broadcast address takes effect. When the receiver is a small part of the network, messages should be sent to multicast groups where only clients added to the group can receive messages. IP addresses ranging from 224.0.0.2 to 244.20.255 are retained as the master unit addresses. The IP address 224.0.0.0 is retained, while 224.0.0.1 is assigned to a fixed group of all IP hosts.

The following example usesUdpclientListen for UDP data packets from the multicast address group 10.0.0.1 on port 8080. It receives the message string and writes the message to the console.

For example, create a project in IDE. The Form class is named formchat. Put a ListBox control on the form to receive messages and a Textbox Control to enter the messages to be sent, put a button to send messages. The full source code is as follows:

Using system;
Using system. drawing;
Using system. collections;
Using system. componentmodel;
Using system. Windows. forms;
Using system. Data;
Using system. net;
Using system. net. Sockets;
Using system. Threading;
Using system. text;
Namespace winudpchat
{
/// <Summary>
/// Summary of form1.
/// </Summary>
Public class formchat: system. Windows. Forms. Form
{
/// <Summary>
/// Required designer variables.
/// </Summary>
Private system. componentmodel. Container components = NULL;
Private Static udpclient m_client;
// Private Static udpclient m_server;

Private Static int listenerports = 8080;
Private Static int senderport = 8080;
Private Static int localport;
Private Static int remoteport;

Private Static string m_szhostname;

Private Static IPaddress m_groupaddress_c;
Private Static IPaddress m_groupaddress_s;
Private Static iphostentry m_localhost;
Private Static ipendpoint m_remoteep;

Private system. Windows. Forms. Button button_sendmsg;
Private system. Windows. Forms. textbox textbox_msg;
Private system. Windows. Forms. ListBox listbox_msg;
Private thread th;
Public formchat ()
{
//
// Required for Windows Form Designer support
//
Initializecomponent ();
//
// Todo: add Any constructor code after initializecomponent calls
//
}
/// <Summary>
/// Clear all resources in use.
/// </Summary>
Protected override void dispose (bool disposing)
{
If (disposing)
{
If (components! = NULL)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}
# Region code generated by Windows Form Designer
/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
Private void initializecomponent ()
{
This. button_sendmsg = new system. Windows. Forms. Button ();
This. textbox_msg = new system. Windows. Forms. Textbox ();
This. listbox_msg = new system. Windows. Forms. ListBox ();
This. suspendlayout ();
//
// Button_sendmsg
//
This. button_sendmsg.location = new system. Drawing. Point (96,234 );
This. button_sendmsg.name = "button_sendmsg ";
This. button_sendmsg.tabindex = 0;
This. button_sendmsg.text = "send ";
This. button_sendmsg.click + = new system. eventhandler (this. button_sendmsg_click );
//
// Textbox_msg
//
This. textbox_msg.location = new system. Drawing. Point (80,197 );
This. textbox_msg.name = "textbox_msg ";
This. textbox_msg.tabindex = 1;
This. textbox_msg.text = "";
//
// Listbox_msg
//
This. listbox_msg.itemheight = 12;
This. listbox_msg.location = new system. Drawing. Point (21, 22 );
This. listbox_msg.name = "listbox_msg ";
This. listbox_msg.size = new system. Drawing. Size (248,136 );
This. listbox_msg.tabindex = 2;
//
// Formchat
//
This. autoscalebasesize = new system. Drawing. Size (6, 14 );
This. clientsize = new system. Drawing. Size (292,273 );
This. Controls. Add (this. listbox_msg );
This. Controls. Add (this. textbox_msg );
This. Controls. Add (this. button_sendmsg );
This. Name = "formchat ";
This. Text = "chat room ";
This. Load + = new system. eventhandler (this. formchat_load );
This. Closed + = new system. eventhandler (this. formchat_closed );
This. resumelayout (false );
}
# Endregion
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main ()
{
Application. Run (New formchat ());
}
Private void formchat_load (Object sender, system. eventargs E)
{
Localport = senderport;
Remoteport = listenerport;
M_szhostname = DNS. gethostname ();

M_localhost = DNS. gethostbyname (m_szhostname );

Initialize ();

Th = new thread (New threadstart (listener ));
Th. Start ();

}
Public void terminate ()
{
M_client.dropmulticastgroup (m_groupaddress_c );
}
Public void initialize ()
{

//
// Instantiate udpclient
//
M_client = new udpclient (localport );

//
// Create the end point of the target host
//
M_groupaddress_s = IPaddress. parse ("10.0.0.1"); // ip address of the computer to be sent
M_remoteep = new ipendpoint (m_groupaddress_s, remoteport );

}
Public void listener ()
{
//
// Create a multicast group object
//
System. net. iphostentry localhost = DNS. gethostbyname (DNS. gethostname ());
String local_ip = localhost. Addresslist [0]. tostring (); // The local IP address for receiving messages, used for listening
M_groupaddress_c = IPaddress. parse (local_ip );

//
// Join Group
//
Try
{
M_client.joinmulticastgroup (m_groupaddress_c, 100); // you can leave it blank for a multicast group.
}
Catch (exception ERR)
{
Throw (ERR); // cannot connect to multicast groups

}

//
// The Listener waits for data to arrive.
// Save it with a buffer.

Thread. Sleep (2000); // ensure that Client2 is receiving

Encoding ASCII = encoding. ASCII;

// While (! M_done)
While (true)
{
Ipendpoint endpoint = NULL;
// Endpoint = new ipendpoint (m_groupaddress_c, localport); // do not use this code.
Byte [] DATA = m_client.receive (ref endpoint );

String strdata = ASCII. getstring (data );
Listbox_msg.items.add (strdata );
}

}
Private void formchat_closed (Object sender, system. eventargs E)
{
Try
{
Try
{
If (Th! = NULL)
{
If (Th. isalive)
{
Th. Abort ();

}

Th = NULL;

}

}
Catch
{
Try
{
System. Threading. thread. resetabort ();
}
Catch
{}
}

Terminate ();
M_client.close ();
}
Catch
{
}
}
Private void button_sendmsg_click (Object sender, system. eventargs E)
{
Byte [] buffer = NULL;

Encoding ASCII = encoding. ASCII;



String S = textbox_msg.text;

Buffer = new byte [S. Length + 1];
//
// Send data to the remote host
//

Int Len = ASCII. getbytes (S. tochararray (), 0, S. length, buffer, 0 );

Int ecode = m_client.send (buffer, Len, m_remoteep );


}
}
}

 

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.