How to realize TCP Communication based on Sockets Class in C #
This article mainly introduces how to achieve TCP communication in C # based on Sockets class, which has a certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let's take a look at it.
The details are as follows
Final effect
TCPClient
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 TCPClient02 {public partial class Form1: Form {public Form1 () {InitializeComponent ();} Socket socketSend Private void button1_Click (object sender, EventArgs e) {/ / Create socket socketSend = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Parse (textBox1.Text); IPEndPoint point = new IPEndPoint (ip, Convert.ToInt32 (textBox2.Text)); IDInfo idinfo = new IDInfo () / / Read ID number information / / Get the IP address and port number of the remote server socketSend.Connect (point); ShowMessages ("Connection succeeded"); / / Start a new thread and keep receiving messages sent by the server Thread th = new Thread (ReciveMessages); th.IsBackground = true; th.Start () } private void button2_Click (object sender, EventArgs e) {string str = textBox3.Text.Trim (); byte [] buffer = System.Text.Encoding.UTF8.GetBytes (str); socketSend.Send (buffer);} void ShowMessages (string str) {textBox4.AppendText (str + "\ r\ n") } void ReciveMessages () {while (true) {byte [] buffer = new byte [1024 * 1024 * 3]; int r = socketSend.Receive (buffer); if (r = = 0) {break } string s = Encoding.UTF8.GetString (buffer, 0, r); ShowMessages (socketSend.RemoteEndPoint + ":" + s);}} private void Form1_Load (object sender, EventArgs e) {Control.CheckForIllegalCrossThreadCalls = false;}
TCPserver
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.Sockets;using System.Net;using System.Threading;namespace TCPserver {public partial class Form1: Form {public Form1 () {InitializeComponent () } private void button1_Click (object sender, EventArgs e) {try {/ / create a Socket Socket socketWatch = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) responsible for listening; / / create an ip address and port number / / IPAddress ip = IPAddress.Parse (textBox1.Text) IPAddress ip = IPAddress.Any; IPEndPoint point = new IPEndPoint (ip, Convert.ToInt32 (textBox2.Text)); / / bind the socket responsible for monitoring to ip address and port number socketWatch.Bind (point); ShowMsg ("listening successful") / / set the listening queue (the maximum number of clients connected at a time) socketWatch.Listen (10); / / the method executed by the thread Thread th = new Thread (Listen); / / the server starts listening th.IsBackground = true; th.Start (socketWatch) } catch {} void ShowMsg (string str) {textBox3.AppendText (str + "\ r\ n");} / wait for the client to connect and create a Socket / Socket socketSend to communicate with it Void Listen (object o) {Socket socketWatch = o as Socket; / / socket responsible for listening to receive client connections / / create socket while (true) {try {socketSend = socketWatch.Accept () ShowMsg (socketSend.RemoteEndPoint.ToString () + "connection successful"); / / start a new thread to receive messages from the client Thread th = new Thread (Recive); th.IsBackground = true; th.Start (socketSend) } catch {} / the server keeps receiving messages from the client / void Recive (object o) {Socket socketSend = o as Socket While (true) {try {/ / after the client connects successfully, the server should receive the message byte [] buffer = new byte [1024 * 1024 * 2] from the client. / / actual received valid bytes int bytelen = socketSend.Receive (buffer); if (bytelen = = 0) {break;} string str = Encoding.UTF8.GetString (buffer, 0, bytelen) ShowMsg (socketSend.RemoteEndPoint + ":" + str) } catch {}} private void textBox1_TextChanged (object sender, EventArgs e) {} private void Form1_Load (object sender, EventArgs e) {Control.CheckForIllegalCrossThreadCalls = false } / the server sends a message to the client / private void button3_Click (object sender, EventArgs e) {string str = textBox4.Text; byte [] buffer = System.Text.Encoding.UTF8.GetBytes (str); socketSend.Send (buffer) } Thank you for reading this article carefully. I hope the article "how to implement TCP Communication based on Sockets" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!