socket向服务器端口发送数据示例
1、socket是什么?
它只是提供了一个针对TCP或者UDP编程的接口,可以进行数据传输。
2、socket向服务器端口传输数据。
(1)引用using System.Net.Sockets;
(2)传输通用接口
public class Program { public void SendData(IPAddress remoteIP, int Port, string bits) { //实例化socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //指定的地址和端口号初始化 IPEndPoint ipep = new IPEndPoint(remoteIP, Port); //建立链接 socket.Connect(ipep); //socket.Send(bits, 8, SocketFlags.None); //byte[] sendBytes = Encoding.UTF8.GetBytes(bits); //传输数据为byte类型数组socket.Send(sendBytes);,如传输string类型直接socket.Send(Encoding.UTF8.GetBytes(bits)); socket.Send(Encoding.UTF8.GetBytes(bits)); //关闭 socket.Close(); } }
(3)调用接口
public class WSsocketController : ApiController
{
/// <summary> /// 调用SendData方法向端口传数据 /// </summary> /// <param name="xx">传入的信息</param> /// <returns></returns> [HttpGet] [ActionName("getKK")] public HttpResponseMessage KK(string xx) { Program pm = new Program(); ResultJson result; HttpResponseMessage resMsg = new HttpResponseMessage(HttpStatusCode.OK); //string order = "你好!";传输字符串类型 //byte[] order = new byte[8]; 传输byte类型数据组 //order = new byte[] { 0x80, 0x04, 0x00, 0x7F }; pm.SendData(IPAddress.Parse("192.168.0.1"), int.Parse("8081"), xx); result = new ResultJson(true, "成功"); resMsg.Content = new ObjectContent<ResultJson>(result, new JsonMediaTypeFormatter()); return resMsg; }
}
总结:简单示例C#实现socket传输数据到服务器端口