udp不是数据报。记得是不分段的吧。
已经解决问题
你好,代码能不能分享一下,我刚学这个
发段保存到数据库不行吧
很简单,把具体的应用场景说一下。
分多个包发送:
private byte[] InsertStartAndEndMark(MsgType msgType, byte[] source) { byte[] result = new byte[source.Length + 1]; result[0] = (byte)msgType; Array.Copy(source, 0, result, 1, source.Length); return result; } public void SendMsg(byte[] data) { SendMsg(data, MsgType.Image); } public void SendMsg(byte[] data, MsgType msgType) { try { //byte[] newData = InsertStartAndEndMark(msgType, data); int offSet = 0; do { byte[] tempData = new byte[(data.Length - offSet) > 60000 ? 60000 : (data.Length - offSet)]; Array.Copy(data, offSet, tempData, 0, tempData.Length); // 加标签 byte[] newData = InsertStartAndEndMark(msgType, tempData); offSet += tempData.Length; sock.SendTo(newData, iep1); } while (data.Length > offSet); } catch (Exception ex) { string s = ""; } }
接收要建立一个临时的List存放未完的数据:
public void Record() { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, Port); sock.Bind(iep); EndPoint ep = (EndPoint)iep; Encoding gb2312 = Encoding.GetEncoding("gb2312"); string lastMsg = string.Empty; List<byte[]> tempDataList = new List<byte[]>(); while (!isDispose) { byte[] source = new byte[1024 * 61]; try { int recv = sock.ReceiveFrom(source, ref ep); MsgType msgType = (MsgType)source[0]; byte[] data = new byte[recv - 1]; Array.Copy(source, 1, data, 0, recv - 1); // 是否分多个包 if (recv >= 60001) { tempDataList.Add(data); continue; } int totalSize = (recv - 1) + (tempDataList.Count == 0 ? 0 : tempDataList.Sum(v => v.Length)); byte[] newData = new byte[totalSize]; int offSet = 0; foreach (byte[] tempByte in tempDataList) { Array.Copy(tempByte, 0, newData, offSet, tempByte.Length); offSet += tempByte.Length; } tempDataList.Clear(); // 加上本次接收的数据 Array.Copy(data, 0, newData, offSet, data.Length); switch (msgType) { case MsgType.Text: string stringData = Encoding.Default.GetString(newData, 0, recv - 1); stringData = crypto.Decrypt(stringData); if (RecordMsgEvent != null) RecordMsgEvent(stringData); break; case MsgType.Image: if (RecordImageEvent != null) RecordImageEvent(newData); break; default: break; } } catch { } } sock.Close(); }
MsgType 这是一个枚举、这代码一次发送和接收60000个字节,如果接收完则触发事件,这里面有两个事件,一个是接收到消息,还有一个是接收到图片,你改进下就行了,我这是自己写的一个UDP聊天程序的代码