Program Introduction
This chat program supports communication between clients and servers in the LAN.
Principle
After the server is started, the server continuously listens for requests sent from the client. Once the information sent from the client is monitored, the two ends can send messages to each other. the server needs to bind an IP address for the client to find and establish a connection in the network. message sending principle: Convert the manually entered string information into a byte array that can be recognized by the machine, and then call the Send () method of the socket to Send the byte array. information receiving principle: Call the Receive () method of the socket to obtain the byte array sent from the peer end, and then convert it to the string information that the adult can understand.
Interface Design-Server
IP text box name: txtIP port (port Number) Text Box name: txtPORT chat content text box name: txtMsg send information text box name: txtSendMsg
Start Service button name: btnServerConn send information button name: btnSendMsg
Server code:
Public partial class FServer: Form {public FServer () {InitializeComponent (); // disable the illegal thread operation on the text box to check the TextBox. checkforillegalcrossthreadcils = false;} Thread threadWatch = null; // listens to the client Thread Socket socketWatch = null; // listens to the client Socket private void btnServerConn_Click (object sender, EventArgs e) {// define a Socket for listening to information sent from the client. It contains three parameters (IP4 Addressing protocol, stream connection, TCP protocol) socketWatch = new Socket (AddressFamily. interNetwork, Socket Type. stream, ProtocolType. tcp); // the IP address and port number IPAddress ipaddress = IPAddress are required for sending information from the server. parse (txtIP. text. trim (); // obtain the IP address entered in the text box // bind the IP address and port number to IPEndPoint endpoint = new IPEndPoint (ipaddress, int. parse (txtPORT. text. trim (); // obtain the port number entered in the text box // listen to the network node socketWatch bound to it. bind (endpoint); // set the length of the socket listening queue to 20 socketWatch. listen (20); // create a listening Thread threadWatch = new Thread (WatchConnecting); // set the form Thread ThreadWatch. IsBackground = true in the background; // Start thread threadWatch. Start (); // After the thread is started, the txtMsg text box displays the corresponding prompt txtMsg. AppendText ("Start listening for client information! "+" \ R \ n ");} // create a Socket socConnection that is responsible for communicating with the client = null; /// <summary> /// listen for requests sent from the client /// </summary> private void WatchConnecting () {while (true) // continuously listen for requests sent from 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 the thr thread. start (socConnection );}} /// <summary> /// Method for sending information to the client /// </summary> /// <param name = "sendMsg"> string information sent </param> private void ServerSendMsg (string sendMsg) {// convert the input string to a byte array that can be recognized by the machine. byte [] arrSendMsg = Encoding. UTF8.GetBytes (sendMsg); // send the byte array information socConnection to the client. send (arrSendMsg); // attaches the sent string information to txtMsg in the text box. appendText ("So-flash:" + GetCurrentTime () + "\ r \ n" + sendMsg + "\ r \ n ");} /// <summary> /// receive information sent from the client /// </summary> /// <param name = "socketClientPara"> client socket object </param> private void ServerRecMsg (object socketClientPara) {Socket socketServer = socketClientPara as Socket; while (true) {// create a memory buffer with a size of 1024*1024 bytes, that is, 1 M byte [] arrServerRecMsg = new byte [1024*1024]; // Save the received information to the memory buffer and return the length of its byte array int length = socketServer. receive (arrServerRecMsg); // converts the byte array received by the machine into a readable string strSRecMsg = Encoding. UTF8.GetString (arrServerRecMsg, 0, length); // attaches the sent string information to txtMsg in the text box. appendText ("Days:" + GetCurrentTime () + "\ r \ n" + strSRecMsg + "\ r \ n ");}} // send the message to the Client private void btnSendMsg_Click (object sender, EventArgs e) {// call the ServerSendMsg method to send the message to the client ServerSendMsg (txtSendMsg. text. trim ();} // Enter to send the message private void txtSendMsg_KeyDown (object sender, KeyEventArgs e) {// if the user presses the Enter key if (e. keyCode = Keys. enter) {// The ServerSendMsg (txtSendMsg) method that calls the server to send messages to the client. text. trim ());}} /// <summary> /// method for obtaining 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 information text box name: txtCMsg
Connect to the server button name: btnBeginListen send message button name: btnSend
Client code:
Public partial class FClient: Form {public FClient () {InitializeComponent (); // disable the illegal thread operation on the text box to check the TextBox. checkforillegalcrossthreadcils = false;} // create a client Socket and a Thread Socket socketClient that listens to server requests = null; Thread threadClient = null; private void btnBeginListen_Click (object sender, eventArgs e) {// define a byte listener that contains three parameters (IP4 Addressing protocol, stream connection, TCP protocol) socketClient = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); // you need to obtain the IP address IPAddress ipaddress = IPAddress in the text box. parse (txtIP. text. trim (); // bind the obtained IP address and port number to IPEndPoint endpoint = new IPEndPoint (ipaddress, int. parse (txtPort. text. trim (); // here, the client socket is used to Connect to the network node (server) instead of Bind socketClient. connect (endpoint); // create a Thread to listen to the message threadClient = new Thread (RecMsg) sent from the server; // set the form Thread to synchronize threadClient with the background. isBackground = true; // start the threadClient thread. start () ;}/// <summary> /// Method for receiving information sent from the server /// </summary> private void RecMsg () {while (true) // continuously listen for messages sent from the server {// defines a 1 MB memory buffer for temporary storage of received information byte [] arrRecMsg = new byte [1024*1024]; // store the data received by the client socket into the memory buffer and obtain the length int length = socketClient. receive (arrRecMsg); // converts the byte array obtained by the socket into a string strRecMsg = Encoding. UTF8.GetString (arrRecMsg, 0, length); // append the message to the text box txtMsg. appendText ("So-flash:" + GetCurrentTime () + "\ r \ n" + strRecMsg + "\ r \ n ");}} /// <summary> /// Method for sending string information to the server // </summary> /// <param name = "sendMsg"> string information sent </ param> private void ClientSendMsg (string sendMsg) {// convert the input content string to the byte array byte [] arrClientSendMsg = Encoding that can be recognized by the machine. UTF8.GetBytes (sendMsg); // call the client socket to send the byte array socketClient. send (arrClientSendMsg); // append the sent information to txtMsg in the chat content text box. appendText ("Days:" + GetCurrentTime () + "\ r \ n" + sendMsg + "\ r \ n ");} // click the btnSend button to send the message private void btnSend_Click (object sender, EventArgs e) {// call the ClientSendMsg method to send the information entered in the text box to the ClientSendMsg (txtCMsg. text. trim ();} // Enter to send the message private void txtCMsg_KeyDown (object sender, KeyEventArgs e) {// when the cursor is in the text box, if the user presses the Enter key on the keyboard if (e. keyCode = Keys. enter) {// call ClientSendMsg (txtCMsg. text. trim ());}} /// <summary> /// method for obtaining the current system time /// </summary> /// <returns> current time </returns> private DateTime GetCurrentTime () {DateTime currentTime = new DateTime (); currentTime = DateTime. now; return currentTime ;}
Running Method
Method for obtaining the IP address of the Local Computer: for example, the local IP Address: 192.168.0.3 (may change) port number can be written as any integer between 1-65535.
1. Open the program and click Run
2. Enter the cmd command in the running column.
3. Enter the command ipconfig to view IP addresses.
4. Obtain the current IP Address: 192.168.0.3. Of course, the local IP address may be different in different places.
Program running display:
First, click the Start Service button on the server. The Chat content displays "Start listening for information sent from the client! "
Click the "connect to server" button on the client to see another line of "client connection succeeded" on the server"
Then the two ends can communicate with each other.
This simple chat program is complete ~~~~ :)
Source code download
Client download ChatClient.zip Server Download ChatServer.zip
Related Recommendations
- Simple chat program based on C # Winform [Article 2-File Sending]
- Simple chat program based on C # Winform [Article 3-message sending]