Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement socket sending and receiving data in C #

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to achieve socket sending and receiving data in C#, which has a certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let the editor take you to know it.

The details are as follows

Server side

Namespace TestServer {public partial class ServerForm: Form {Socket socketSend; / / stores the IP address and socket of remotely connected clients in the collection Dictionary dicSocket = new Dictionary (); public ServerForm () {InitializeComponent () } private void btnStart_Click (object sender, EventArgs e) {try {/ / when you click to start listening, create a socket Socket socketWatch = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) on the server to listen for the IP address and port number; IPAddress ip = IPAddress.Any;// IPAddress.Parse (txtServer.Text) IPEndPoint point = new IPEndPoint (ip, Convert.ToInt32 (txtPort.Text)); / / Monitoring socketWatch.Bind (point); ShowMsg ("listening successfully"); socketWatch.Listen (10); Thread th = new Thread (Listen); th.IsBackground = true Th.Start (socketWatch);} catch {}} void Listen (object o) {/ / wait for the client to connect and create a Socket Socket socketWatch = o as Socket; while (true) {socketSend = socketWatch.Accept () responsible for communication DicSocket.Add (socketSend.RemoteEndPoint.ToString (), socketSend); cboUsers.Items.Add (socketSend.RemoteEndPoint.ToString ()); ShowMsg (socketSend.RemoteEndPoint.ToString () + ":" + "connection successful"); Thread th = new Thread (Recive); th.IsBackground = true; th.Start (socketSend) }} void Recive (object o) {socketSend = o as Socket; while (true) {/ / after the client connects successfully, the server should accept the message byte [] buffer = new byte [1024 * 1024 * 2] from the client. / / actual received valid bytes int r = socketSend.Receive (buffer); if (r = 0) {break;} string str = Encoding.UTF8.GetString (buffer, 0, r); ShowMsg (socketSend.RemoteEndPoint + ":" + str) }} void ShowMsg (string str) {txtLog.AppendText (str + "\ r\ n");} private void Form1_Load (object sender, EventArgs e) {Control.CheckForIllegalCrossThreadCalls = false;} private void btnSend_Click (object sender, EventArgs e) {string str = txtMsg.Text Byte [] buffer = Encoding.UTF8.GetBytes (str); string ip = cboUsers.SelectedItem.ToString (); Dicket [IP] .send (buffer); / / socketSend.Send (buffer); txtMsg.Text = "";} private void btnSendUser_Click (object sender, EventArgs e) {string json = JsonConvert.SerializeObject (UserList ()) Byte [] buffer = Encoding.UTF8.GetBytes (json); socketSend.Send (buffer);} private List UserList () {List userList = new List (); User user = null; string sql = "select * from user_table"; SqlCommand cmd = SqlUtils.ConnectSql (sql); SqlDataReader sdr = cmd.ExecuteReader () While (sdr.Read ()) {user = new User (sdr.GetInt32 (0), sdr.GetString (1), sdr.GetString (2), sdr.GetInt32 (3)); userList.Add (user);} return userList;} client

Namespace TestClient {public partial class ClientForm: Form {Socket socketSend; public ClientForm () {InitializeComponent ();} private void btnStart_Click (object sender, EventArgs e) {try {/ / create socket socketSend = new Socket (AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp) responsible for communication IPAddress ip = IPAddress.Parse (txtServer.Text); IPEndPoint point = new IPEndPoint (ip,Convert.ToInt32 (txtPort.Text)); socketSend.Connect (point); ShowMsg ("connected successfully"); Thread th = new Thread (Recive); th.IsBackground = true; th.Start () } catch {} void Recive () {while (true) {/ / after the client connection is successful, the server should accept the message byte [] buffer = new byte [1024 * 1024 * 2] from the client. / / actual received valid bytes int r = socketSend.Receive (buffer); if (r = 0) {break;} string str = Encoding.UTF8.GetString (buffer, 0, r); ShowMsg (socketSend.RemoteEndPoint + ":" + str) }} void ShowMsg (string str) {txtLog.AppendText (str + "\ r\ n");} private void Form1_Load (object sender, EventArgs e) {Control.CheckForIllegalCrossThreadCalls = false;} private void btnSend_Click (object sender, EventArgs e) {string str = txtMsg.Text.Trim () Byte [] buffer = Encoding.UTF8.GetBytes (str); socketSend.Send (buffer); txtMsg.Text = "";}

Effect.

Send json data

Thank you for reading this article carefully. I hope the article "how to send and receive data by socket" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report