C# Socket Send: Client Communication Guide
In C#, you can specify the client to send information using the Send method of the Socket object. Here is a simple example code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static void Main()
{
// 创建一个Socket对象
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 连接到服务器
socket.Connect("127.0.0.1", 8888);
// 发送消息给服务器
string message = "Hello, server!";
byte[] data = Encoding.ASCII.GetBytes(message);
socket.Send(data);
// 关闭Socket连接
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
In the example above, a Socket object is first created and connected to the server’s IP address and port number. Then, the message to be sent is converted to a byte array and sent to the server using the Send method. Finally, the Socket connection is closed.