Use SOCKET as a LAN chat tool

Source: Internet
Author: User

ProgramIt is designed to be a simple communication between the server and the client, but some methods can be used to unify the two, so that the server also becomes the client, so that the client also becomes the server, enable communication between them at any time. considering the steps required to implement the original communication between the server and the client, it is very helpful to write such a program.

As a server, you must declare a socket A and bind it to an IP address + the communication port specified by this IP address.For example, this is 127.0.0.1: 9050,Then start listening (Listen). Listen can listen to connection requests sent from multiple IP addresses.You can connect to several clients at the same time. You can set a parameter in the listen method.If listen sends a connection request to a client, a new socket B is defined to communicate with the client. Socket B = A. Accept ().You can obtain the IP address and port of the client. ipendpoint c = (ipendpoint) B. remoteendpoint, C. Address, and C. Port indicate the IP address and port of client C respectively.In this case, the B. Send () method can be used to send messages to C. B. Receive () can receive messages sent from client C.

As a client, you also need to declare a socket d and bind an IP address + an unused port on the local machineDefine ipendpoint e to indicate the socket of the server to be connected. Specify the IP address and port of E to allow communication between ports,Next we can try D. Connect (e ),After successful connection, you can send and receive data,D. Send (), D. Receive.

When a message is sent,Data is transmitted in bytes or byte arrays.For example, if my client D wants to send "Hello World", write it as follows: D. send (encoding. ASCII. getbytes ("Hello World ")). when receiving a message, it is also a byte or byte array. For example, if the server wants to accept the Hello world that d just sent, you can write as follows: byte [] DATA = new byte [1024]; int receiveddatalength = B. receive (data); string stringdata = encoding. ASCII. getstring (data, 0, receiveddatalength); stringdata is Hello world.

The above is just a rough description of the communication process between the server and the client.CodeThis example does not unify the server and the client. It is written to the server and the client respectively.

Server code
Using system; using system. Net; using system. net. Sockets; using system. Text; namespace tcpserver {// <summary> // class1 abstract description. /// </Summary> class server {/// <summary> /// main entry point of the application. /// </Summary> [stathread] Static void main (string [] ARGs) {// todo: Add code here to start the application // int Recv; // indicates the length of the information sent by the client. byte [] data; // = new byte [1024]; // indicates the information sent by the client, the information passed through the socket must be a byte array ipendpoint ipep = new ipendpoint (IPaddress. any, 9050); // the IP address and port socket newsock = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); newsock. BIND (ipep); // bind newsock. listen (10); // listen to the console. writeline ("waiting for a client"); Socket Client = newsock. accept (); // executed when an available client connection attempt is made and a new socket is returned for communication with the client ipendpoint clientip = (ipendpoint) client. remoteendpoint; console. writeline ("Connect with client:" + clientip. address + "at Port:" + clientip. port); string welcome = "welcome here! "; Data = encoding. ASCII. getbytes (welcome); client. send (data, data. length, socketflags. none); // send information while (true) {// use an endless loop to continuously obtain information from the client data = new byte [1024]; Recv = client. receive (data); console. writeline ("Recv =" + Recv); If (Recv = 0) // when the information length is 0, the client is disconnected from break; console. writeline (encoding. ASCII. getstring (data, 0, Recv); client. send (data, Recv, socketflags. none);} console. writeline ("disconnected from" + clientip. address); client. close (); newsock. close ();}}}
Client code
Using system; using system. Net; using system. net. Sockets; using system. Text; namespace tcpclient {/// <summary> /// class1 abstract description. /// </Summary> class client {/// <summary> /// main entry point of the application. /// </Summary> [stathread] Static void main (string [] ARGs) {// todo: add code here to start the application // byte [] DATA = new byte [1024]; socket newclient = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); newclient. BIND (New ipendpoint (IPaddress. any, 905); console. write ("Please input the Server IP:"); string ipadd = console. readline (); console. writeline (); console. write ("Please inpu T the server port: "); int Port = convert. toint32 (console. readline (); ipendpoint Ie = new ipendpoint (IPaddress. parse (ipadd), Port); // server IP address and port try {// because the client is only used to send information to a specific server, you do not need to bind the local IP address and port. You do not need to listen. Newclient. connect (IE);} catch (socketexception e) {console. writeline ("unable to connect to server"); console. writeline (E. tostring (); return;} int receiveddatalength = newclient. receive (data); string stringdata = encoding. ASCII. getstring (data, 0, receiveddatalength); console. writeline (stringdata); While (true) {string input = console. readline (); If (input = "exit") break; newclient. send (encoding. ASCII. getbytes (input); Data = new byte [1024]; receiveddatalength = newclient. receive (data); stringdata = encoding. ASCII. getstring (data, 0, receiveddatalength); console. writeline (stringdata);} console. writeline ("disconnect from sercer"); newclient. shutdown (socketshutdown. both); newclient. close ();}}}

The preceding server and client are both console applications. The idea of creating a form is to create another thread, which is responsible for establishing connections between the two ends. if you do not use another thread method, the program will be in a dead state if no connection is waiting for the connection or the server is actively connected, but the server is not responding.

After the thread successfully connects the two ports, the program enters an endless loop. This endless loop is responsible for continuously receiving messages, and the output is displayed in txtgetmsg:

While (true) // uses an endless loop to continuously obtain information {DATA = new byte [1024]; Recv = newclient. receive (data); uicontext. send (New sendorpostcallback (State => {int txtgetmsglength = txtgetmsg. text. length; string recmsg = "friend:" + system. datetime. now. tostring () + "\ n" + encoding. unicode. getstring (data, 0, Recv) + "\ n"; txtgetmsg. appendtext (recmsg); txtgetmsg. select (txtgetmsglength, recmsg. length-encoding. unicode. getstring (data, 0, Recv ). length-1); txtgetmsg. selectioncolor = color. red;}), null );}

If you press the send message button, the text in txtsendmsg will be sent. I write unicode encoding, so Chinese characters can be sent.

Private void btnsendmsg_click (Object sender, eventargs e) {string input = txtsendmsg. Text; If (input = "") {MessageBox. Show ("The message cannot be blank! "," Message sending error "); txtsendmsg. focus ();} else {If (meisclient) {newclient. send (encoding. unicode. getbytes (input); string showtext = "me:" + system. datetime. now. tostring () + "\ n" + input + "\ n"; int txtgetmsglength = txtgetmsg. text. length; txtgetmsg. appendtext (showtext); txtgetmsg. select (txtgetmsglength, showtext. length-1-input. length); txtgetmsg. selectioncolor = color. blue; txtsendmsg. TEXT = "";} else {client. send (encoding. unicode. getbytes (input); string showtext = "me" + system. datetime. now. tostring () + "\ n" + input + "\ n"; int txtgetmsglength = txtgetmsg. text. length; txtgetmsg. appendtext (showtext); txtgetmsg. select (txtgetmsglength, showtext. length-1-input. length); txtgetmsg. selectioncolor = color. blue; txtsendmsg. TEXT = "";}}}
Program Running Effect

:/Files/technology/local network tool. Zip

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.