public bool recv_packet(ref packet pk) { int ret = 0; if (!_get_header) { ret = _sock.Receive(_head_buff, (int)_offset, (int)(_expect_len - _offset), SocketFlags.None); } else { ret = _sock.Receive(_data_buff, (int)_offset, (int)(_expect_len - _offset), SocketFlags.None); } if (ret <= 0) { vesal_log.vesal_write_log("ret error"); // link broken. throw new ArgumentNullException("value");; } _offset += (uint)ret; if (_offset == _expect_len) { _offset = 0; if (!_get_header) { // 包头接收完毕。 _get_header = true; _expect_len = get_pack_len(_head_buff); return(false); } else { // 一个包收完了。 _get_header = false; //输出包 pk._cmd_code = _head_buff[0]; pk._data_len = _expect_len; pk._data = new byte[_expect_len]; for (int j = 0; j < _expect_len; j++) { pk._data[j] = _data_buff[j]; } _expect_len = packet._head_len; return(true); } } return(false); }
public override void on_packet_recved(vesal_socket vsock, packet pk) { base.on_packet_recved(vsock, pk); byte[] buff = new byte[pk._data_len]; for (int j = 0; j < pk._data_len; j++) { buff[j] = pk._data[j]; } //DebugLog.DebugLogInfo("ff0000", buff.Length + ""); //接收 OnpeerRecive(vsock, pk._cmd_code, buff); // string str = System.Text.Encoding.UTF8.GetString(buff); // if (pk._cmd_code == (byte)VESAL_CMD_CODE.MSG_CMD) // { // UnityEngine.Debug.Log("realMessage:" + str); // OnpeerRecive(str); // } }
virtual public void on_packet_recved(vesal_socket vsock, packet pk) { //Console.WriteLine("{0} recv packet.", vsock.fd()); }
//写数据时,socket broken public void work() { if (_listen_socks.Count > 0) { ArrayList sockList = new ArrayList(); foreach (var item in _listen_socks) { sockList.Add(item.Value._sock); } Socket.Select(sockList, null, null, 0); for (int i = 0; i < sockList.Count; i++) { vesal_socket vsock = _listen_socks[(int)((Socket)sockList[i]).Handle]; vesal_socket newsock = vsock.accept(); _comm_socks[(int)newsock._sock.Handle] = newsock; on_peer_connected(newsock); } } if (_comm_socks.Count > 0) { List <int> bad_socks = new List <int>(); ArrayList sockList2 = new ArrayList(); foreach (var item in _comm_socks) { sockList2.Add(item.Value._sock); } Socket.Select(sockList2, null, null, 0); for (int i = 0; i < sockList2.Count; i++) { int fd = (int)((Socket)sockList2[i]).Handle; vesal_socket vsock = _comm_socks[fd]; try { packet pk = new packet(); bool getpack = vsock.recv_packet(ref pk); if (getpack) { on_packet_recved(vsock, pk); } } catch (Exception e) { //Console.WriteLine("link read bad"); bad_socks.Add(fd); } } clean_bad_fd(bad_socks); foreach (var item in _comm_socks) { if (item.Value.has_data()) { bool ret = item.Value.send_data(); if (!ret) { //Console.WriteLine("link send bad"); bad_socks.Add(item.Key); } } } clean_bad_fd(bad_socks); } }