Soket 连接发送与接收
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | ///url:地址 data:数据 public static string GetContentFromUrl( string url, string data) { //寻址方案。ip4地址 // 套接字类型 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ip = new IPEndPoint(IPAddress.Parse(url), 端口); socket.Connect(ip); //连接 char [] cmgs = data.ToCharArray(); //字符串转字符数组 byte [] message = new byte [1024]; message = Encoding.UTF8.GetBytes(data); socket.Send(message); //发送数据 byte [] bytes = new byte [1024]; socket.Receive(bytes); //接收数据 string messages = Encoding.Default.GetString(bytes, 0, bytes.Length); return messages; //返回数据 socket.Close(); } |
/// <summary> /// 连接服务 接收大数据量 /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <returns></returns> public static string GetContentFromUrl(string url, string data) { Socket sokClient = null; string Message = ""; try { sokClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress address = IPAddress.Parse(url); IPEndPoint point = new IPEndPoint(address, 8108); sokClient.Blocking = true; //没有数据接受时挂起等待, 知道有数据时 sokClient.Connect(point); char[] cmgs = data.ToCharArray(); //字符串转字符数组 byte[] message = new byte[1024]; message = Encoding.Default.GetBytes(data); sokClient.Send(message);
byte[] totalBytes = null; int receiveLength = 0; do { byte[] buffer = new byte[1024]; receiveLength = sokClient.Receive(buffer, buffer.Length,0); //接受数据长度 if (totalBytes == null) //第一次接收数据 { totalBytes = new byte[receiveLength]; //声明byte
//从指定数组的 位置 复制到另一数组的指定位置 Buffer.BlockCopy(buffer, 0, totalBytes, 0, receiveLength); } else { byte[] appendBytes = new byte[receiveLength]; Buffer.BlockCopy(buffer, 0, appendBytes, 0, receiveLength); byte[] newTotalBytes = new byte[receiveLength + totalBytes.Length]; Buffer.BlockCopy(totalBytes, 0, newTotalBytes, 0, totalBytes.Length); Buffer.BlockCopy(appendBytes, 0, newTotalBytes, totalBytes.Length, appendBytes.Length); totalBytes = newTotalBytes; } } while (receiveLength > 0 && receiveLength == 1024); Message = Encoding.Default.GetString(totalBytes); return Message; } catch (Exception ex) { return ex.Message; } finally { sokClient.Close(); } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步