Use udpclient to write chat programs

Source: Internet
Author: User

UseUdpclientWriteChat Program

UdpclientClass usageUDPCommunicate with network services.UDPIt is easy to use and can broadcast messages to multiple addresses at the same time. HoweverUDPThe Protocol is a connectionless protocol, so it is sent to the remote endpointUDPData packets may not arrive at the same time or in the same order of sending. UseUDPThe application must be prepared to handle the lost and wrong data packets.

To useUDPTo send a data packet, you must know the network address of the network device that carries the required service andUDPThe port number.

Special network addresses are used to supportIPOn the networkUDPBroadcast messages. The content discussed below is as follows:InternetUsed onIPVersion4Address family as an example.

IPVersion4Address usage32Bit specifies the network address. For255.255.255.0Network maskCClass address, which is divided into four eight bytes. When expressed in decimal number, these four eight-bit bytes constitute a familiar four-part notation separated by points, such192.168.100.2. The first two eight bytes (in this example192.168) Indicates the network number, which is the third octal byte.(100)Defines the subnet; the last eight bytes(2)Is the host identifier.

SetIPAll bits of the address are set1(That is255.255.255.255) Can constitute a limited broadcast address. SetUDPData packets are sent to this address to pass 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 addresses1To direct the broadcast to a specific part of the network. For example, to send a broadcast192.168HeadersIPFor all hosts on the network identified by the address, set the subnet and host part of the address1, Such192.168.255.255. To restrict the broadcast to a single subnet, set only the host part1, Such192.168.100.255.

Udpclient Class can broadcast to any network broadcast address, but it cannot listen to broadcasts sent to the network. RequiredSocket Class.

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. Range from224.0.0.2To244.00000000255OfIPThe address is retained as the master unit address.IPNo.224.0.0.0Is retained, while224.0.0.1Assigned to allIPA fixed group of hosts.

The following example usesUdpclient Listener Port8080Multicast address group on10.0.0.1OfUDPData message broadcast. It receives the message string and writes the message to the console.

For exampleIDECreate a project and name the Form classFormchat, Put a control on the formListBox, Used to receive messages, putTextboxControl is used to input the message to be sent, putButtonUsed to send messages. AllSource codeAs 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 after initializecomponent callsCode
//
}

/// <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 );
 

}

}
}

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.