1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| public class NetAsyncMgr : MonoBehaviour { private static NetAsyncMgr instance; public static NetAsyncMgr Instance => instance; private Socket socket; private byte[] cacheByte = new byte[1024*1024]; private int cacheNum = 0; void Awake() { instance = this; DontDestroyOnLoad(this.gameObject); }
void Update() { } public void Connect(string ip, int port) { if(socket!=null&&socket.Connected) return; IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(ip), port); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = ipPoint; args.Completed += (socket, args) => { if (args.SocketError == SocketError.Success) { print("链接成功"); SocketAsyncEventArgs receiveArgs = new SocketAsyncEventArgs(); receiveArgs.SetBuffer(cacheByte, 0, cacheByte.Length); receiveArgs.Completed += ReceiveCallback; this.socket.ReceiveAsync(receiveArgs); } else { print("链接失败"+args.SocketError); } }; socket.ConnectAsync(args); } private void ReceiveCallback(object sender, SocketAsyncEventArgs args) { if (args.SocketError == SocketError.Success) { print(Encoding.UTF8.GetString(args.Buffer, 0, args.BytesTransferred)); args.SetBuffer(cacheByte, 0, cacheByte.Length); if (socket!=null && this.socket.Connected) socket.ReceiveAsync(args); else Close(); } else { print("接收消息出错"+args.SocketError); Close(); } } public void Close() { if (socket != null) { socket.Shutdown(SocketShutdown.Both); socket.Disconnect(false); socket.Close(); socket = null; } }
public void Send(string str) { if (socket != null && this.socket.Connected) { byte[] bytes = Encoding.UTF8.GetBytes(str); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.SetBuffer(bytes, 0, bytes.Length); args.Completed += (socket, args) => { if (args.SocketError != SocketError.Success) { print("发送消息失败"+args.SocketError); Close(); } }; this.socket.SendAsync(args); } else { Close(); } } }
|