Program Introduction
This chat program supports mutual communication between client and server on LAN.
Principle
After the server is started, the service side listens to the client's request, and once it hears the information from the client, the two ends can send the information to each other. The server needs to bind an IP for the client to find and establish a connection in the network. The principle of information transmission: Converts the manual input string information into a machine-readable array of bytes, and then calls the Send () method of the socket to send a byte array. Message Reception principle: Call the Receive () method of the socket, get the byte array transmitted to the end, and then convert the string information that the adult can read.
Interface design- service side
IP text box name:txtip port (port number) text box name:txtport chat content text box name:txtmsg send info text box name:txtsendmsg
Start Service button name:btnserverconn Send Message button name:btnsendmsg
Service-Side code:
Public partial class Fserver:form {public Fserver () {InitializeComponent (); Turn off illegal thread operations on text boxes Check textbox.checkforillegalcrossthreadcalls = false; } Thread threadwatch = null; The thread that is responsible for listening to the client Socket socketwatch = null; Socket for listener client private void Btnserverconn_click (object sender, EventArgs e) {//define a socket for listening to the message sent by the client Contains 3 parameters (IP4 Addressing protocol, streaming connection, TCP protocol) Socketwatch = new Socket (AddressFamily.InterNetwork, SocketType.Stream, Protocolt Ype. TCP); The server sends a message requiring 1 IP addresses and port numbers IPAddress IPAddress = Ipaddress.parse (TxtIP.Text.Trim ()); Get the IP address of the text box input//Bind the IP address and port number to the network node endpoint on IPEndPoint endpoint = new IPEndPoint (ipaddress, Int. Parse (TxtPORT.Text.Trim ())); Gets the port number entered on the text box//monitoring the Bound network node Socketwatch.bind (endpoint); Limit the listening queue length of the socket to Socketwatch.listen (20); Create a listener thread Threadwatch = new Thread (WATChconnecting); Set the form thread to synchronize with background Threadwatch.isbackground = true; Start thread Threadwatch.start (); After starting the thread txtmsg the text box to display the corresponding prompt Txtmsg.appendtext ("Start listening to the message from the client!" + "\ r \ n"); }//Create a socket that is responsible for communicating with the client socket socconnection = NULL; <summary>////listening to requests from clients///</summary> private void watchconnecting () { while (true)//continuously listens for requests sent by the client {socconnection = Socketwatch.accept (); Txtmsg.appendtext ("Client connection succeeded" + "\ r \ n"); Create a communication thread parameterizedthreadstart pts = new Parameterizedthreadstart (serverrecmsg); Thread thr = new Thread (pts); Thr. IsBackground = true; Start thread thr. Start (socconnection); }}///<summary>///For sending information to the client///</summary>//<param name= "Sendms G "> String information sent </param> private void Serversendmsg (string sendmsg) {//converts the input string to a machine-recognized byte array byte[ ] Arrsendmsg = Encoding.UTF8.GetBytes (sendmsg); Sends byte array information to the client socconnection.send (ARRSENDMSG); Attaches the sent string information to the text box txtmsg on Txtmsg.appendtext ("So-flash:" + getcurrenttime () + "\ r \ n" + sendmsg + "\ r \ n"); }///<summary>//Receive information from clients///</summary>//<param name= "socketclientpa RA > Client socket object </param> private void Serverrecmsg (object Socketclientpara) {Socket SocketS erver = Socketclientpara as Socket; while (true) {//Creates a memory buffer with a size of 1024*1024 bytes that is 1M byte[] arrserverrecmsg = new byte [1024 * 1024]; The received information is deposited into the memory buffer and returns the length of its byte array int length = socketserver.receive (arrserverrecmsg); Converts a machine-accepted byte array into a human-readable string strsrecmsg = Encoding.UTF8. GetString (arrserverrecmsg, 0, length); Attaches the sent string information to the text box txtmsg on Txtmsg.appendtext ("Days of the Kayak:" + getcurrenttime () + "\ r \ n" + strsrecmsg + "\ r \ n"); }}//Send message to client private void Btnsendmsg_click (object sender, EventArgs e) { Call the Serversendmsg method to send the message to the client serversendmsg (TxtSendMsg.Text.Trim ()); }//shortcut key enter send message private void Txtsendmsg_keydown (object sender, KeyEventArgs e) {//IF The user presses the Enter key if (E.keycode = = Keys.enter) {//the method server that invokes the server to send information to the client Sendmsg (TxtSendMsg.Text.Trim ()); }}///<summary>///How to get the current system time///</summary>//<returns> Current time < ;/returns> private datetime GetCurrentTime () {datetime currenttime = new DateTime (); CurrentTime = DateTime.Now; return currenttime; }
Interface Design-Client
IP text box name:txtip port text box name:txtport chat content text box name:txtmsg send info text box name:txtcmsg
Connect to service-side button name:btnbeginlisten Send Message button name:btnsend
Client code:
Public partial class Fclient:form {public fclient () {InitializeComponent (); Turn off illegal thread operations on text boxes Check textbox.checkforillegalcrossthreadcalls = false; }//create 1 Client sockets and a thread responsible for listening for server requests socket socketclient = NULL; Thread threadclient = null; private void Btnbeginlisten_click (object sender, EventArgs e) {//define a set of byte listeners with 3 parameters (IP4 Addressing protocol, streaming connection, TCP protocol) Socketclient = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); You need to get the IP address in the text box IPAddress IPAddress = Ipaddress.parse (TxtIP.Text.Trim ()); Bind the obtained IP address and port number to the network node endpoint on IPEndPoint endpoint = new IPEndPoint (ipaddress, Int. Parse (TxtPort.Text.Trim ())); Here the client socket is connected to the network node (server side) using Connect instead of bind Socketclient.connect (endpoint); Create a thread to listen for messages from the service side threadclient = new Thread (RECMSG); Set the form thread to synchronize with the background threAdclient.isbackground = true; Start thread Threadclient.start (); }///<summary>///Receive information from the server///</summary> private void recmsg () { while (true)//continuously listens for messages sent by the server {//define a 1M memory buffer for temporary storage of received information byte[] ARRRECM SG = new byte[1024 * 1024]; The data received by the client socket is stored in a memory buffer, and its length of int length = Socketclient.receive (arrrecmsg) is obtained; Converts a socket to an array of bytes that can be read by a human string strrecmsg = Encoding.UTF8.GetString (arrrecmsg, 0, length); Append the sent information to the Chat content text box Txtmsg.appendtext ("So-flash:" + getcurrenttime () + "\ r \ n" + strrecmsg + "\ r \ n"); }}///<summary>///Send string information to the server////</summary>//<param N Ame= "sendmsg" > string information sent </param> private void clientsendmsg (string sendmsg) {//To go to the input content string Change to a machine-recognized byte array byte[]Arrclientsendmsg = Encoding.UTF8.GetBytes (sendmsg); Call the client socket to send the byte array socketclient.send (ARRCLIENTSENDMSG); Append the sent information to the Chat content text box Txtmsg.appendtext ("Days of the Kayak:" + getcurrenttime () + "\ r \ n" + sendmsg + "\ r \ n"); }//Click button btnsend Send message to server private void Btnsend_click (object sender, EventArgs e) {//Call Clie The Ntsendmsg method sends the information entered in the text box to the server Clientsendmsg (TxtCMsg.Text.Trim ()); }//shortcut key to send message private void Txtcmsg_keydown (object sender, KeyEventArgs e) {//When the cursor is in text box if the user presses the Enter key on the keyboard if (E.keycode = = Keys.enter) {//invokes the method by which the client sends information to the server Clientsendmsg (TxtCMsg.Text.Trim ()); }}///<summary>///How to get the current system time///</summary>//<returns> Current time < ;/returns> private datetime GetCurrentTime () {datetime currenttime = new DateTime (); CUrrenttime = DateTime.Now; return currenttime; }
How to Run
To obtain a computer's native IP: For example: Native ip:192.168.0.3 (Possible change) port number port can be arbitrarily written: any integer between 1-65535 lines
1. Open the program click Run
2. Enter the cmd command in the Run bar
3. Enter the view IP command: ipconfig
4. Get the current ip:192.168.0.3. Of course, different places. Native IP may not be the same
Program Run Show:
First click on the service side of the Start Service button chat content appears "Start listening to the message from the client!"
Then click on the "Connect to server Side" button on the client to see another line on the server "client connection succeeded"
Then you can communicate on both ends.
Such a simple chat program is finished ~ ~ ~ ~ ~ ~:)
Source code Download
Client download chatclient.zip server download Chatserver.zip
Note: This article goes to http://www.cnblogs.com/longwu/archive/2011/08/25/2153636.html