In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is to share with you about how to use C # Socket-based TCP communication to implement chat rooms. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
The details are as follows
I. the concept of socket communication
Socket is the cornerstone of communication, which is used to describe the address and port of IP. It is the handle of a communication chain and can be used to realize the communication between different virtual machines or different computers. It is the basic operation unit of network communication that supports TCP/IP protocol. It is the abstract representation of the endpoint in the process of network communication, and contains five kinds of information necessary for network communication: the protocol used for the connection, the IP address of the local host, the protocol port of the local process, the IP address of the remote host, and the protocol port of the remote process.
When the application layer communicates data through the transport layer, TCP will encounter the problem of providing concurrent services for multiple application processes at the same time. Multiple TCP connections or multiple application processes may need to transfer data through the same TCP protocol port. In order to distinguish different application processes and connections, many computer operating systems provide socket (Socket) interfaces for applications to interact with TCP/IP protocols. The application layer and the transport layer can distinguish the communication from different application processes or network connections through the Socket interface, and realize the concurrent service of data transmission.
2. Establish socket connection
Establishing a Socket connection requires at least a pair of sockets, one of which runs on the client side, called ClientSocket, and the other runs on the server side, called ServerSocket.
The connection process between sockets is divided into three steps: server monitoring, client request, and connection confirmation.
1. Server monitoring: server-side sockets do not locate specific client sockets, but are waiting for connections, monitoring network status in real time and waiting for connection requests from clients.
2. Client request: refers to the connection request made by the socket of the client, and the target of the connection is the socket on the server side. To do this, the client socket must first describe the socket of the server it wants to connect to, indicate the address and port number of the server-side socket, and then make a connection request to the server-side socket.
3. Connection confirmation: when the server socket monitor hears or receives the connection request of the client socket, it responds to the request of the client socket, establishes a new thread, and sends the description of the server socket to the client. Once the client confirms this description, the two parties formally establish a connection. The server-side socket continues to listen and continues to receive connection requests from other client sockets.
III. SOCKET connection and TCP connection
When you create a Socket connection, you can specify the transport layer protocol to use, and Socket can support different transport layer protocols (TCP or UDP), and when using the TCP protocol to connect, the Socket connection is a TCP connection.
Socket communication: divided into synchronous and asynchronous communication, the two ends of the communication are the client (Client) and the server (Server), this paper briefly introduces the synchronous communication and the case.
Chat room case server
Using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.Net;using System.Net.Sockets;using System.Threading; namespace server {public partial class Form1: Form {public Form1 () {InitializeComponent () / in multithreaded programming, cancel CheckForIllegalCrossThreadCalls = false;} IDictionary clientList = new Dictionary () if you need to use the main thread; private void button1_Click (object sender, EventArgs e) {Thread th = new Thread (StartSever); th.IsBackground = true; th.Start () } void StartSever () {/ / 1. Create a server phone Socket server = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); / / 2. Create a mobile phone card IPAddress ip = IPAddress.Parse (txtIP.Text); / / convert ip and port to IPEndPoint instance IPEndPoint endpoint = new IPEndPoint (ip, int.Parse (txtPort.Text)); / / 3. Insert the phone card into the phone and bind the port server.Bind (endpoint); / / 4. Start monitoring the phone server.Listen (20); listMsg.Items.Add ("Server started successfully"); / / 5. Waiting for while (true) {/ / to receive access to a client Socket connectClient = server.Accept (); if (connectClient! = null) {string infor = connectClient.RemoteEndPoint.ToString (); clientList.Add (infor, connectClient) ListMsg.Items.Add (infor+ "join server"); string msg = infor+ "entered chat room successfully"; SendMsg (msg); Thread thread = new Thread (ReciveMsg); thread.IsBackground = true; thread.Start (connectClient) } void ReciveMsg (object o) {Socket client = o as Socket; while (true) {try {byte [] arrMsg = new byte [1024 * 1024]; int length = client.Receive (arrMsg) If (length > 0) {string recMsg = Encoding.UTF8.GetString (arrMsg, 0, length); IPEndPoint endpoint = client.RemoteEndPoint as IPEndPoint; listMsg.Items.Add (DateTime.Now + "[" + endpoint.Port.ToString () + "]" + recMsg) SendMsg ("[" + endpoint.Port.ToString () + "]" + recMsg);} catch (Exception) {client.Close (); clientList.Remove (client.RemoteEndPoint.ToString ()) } private void label1_Click (object sender, EventArgs e) {string ip = IPAddress.Any.ToString (); txtIP.Text = ip } void SendMsg (string str) {foreach (var item in clientList) {byte [] arrMsg = Encoding.UTF8.GetBytes (str); item.Value.Send (arrMsg) }} private void button2_Click (object sender, EventArgs e) {if (txtMsg.Textlines = "") {SendMsg (txtMsg.Text);}
Client
Using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.Net;using System.Net.Sockets;using System.Threading;namespace server 2.room12 {public partial class Form1: Form {public Form1 () {InitializeComponent (); CheckForIllegalCrossThreadCalls = false;} Socket Client Private void button1_Click (object sender, EventArgs e) {/ / create server phone Client = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); / / create mobile phone card IPAddress ip = IPAddress.Parse (txtIP.Text); IPEndPoint endinput = new IPEndPoint (ip, int.Parse (txtport.Text)); Client.Connect (endinput) Thread th = new Thread (ReciveMsg); th.IsBackground = true; th.Start (Client);} void ReciveMsg (object o) {Socket client = o as Socket; / / 5. Waiting for a call while (true) {byte [] arrlist = new byte [1024,1024]; int length = client.Receive (arrlist); string msg = DateTime.Now + Encoding.UTF8.GetString (arrlist,0,length); listmsg.Items.Add (msg) }} private void button2_Click (object sender, EventArgs e) {if (txtinput.Textlegs null) {SendMsg (txtinput.Text);}} void SendMsg (string msg) {byte [] arrMsg = Encoding.UTF8.GetBytes (msg); Client.Send (arrMsg) Thank you for your reading! This is the end of the article on "how to use C # Socket-based TCP communication to achieve chat rooms". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.