public bool SocketConnection(string LocalIP, int LocalPort) { mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IPAddress ip = IPAddress.Parse(LocalIP); IPEndPoint ipe = new IPEndPoint(ip, LocalPort); mSocket.Connect(ipe); WireProtocolFactory = new MyWireProtocolFactory(); WireProtocol = WireProtocolFactory.CreateWireProtocol(); WireProtocol.Reset(); msgQueue = new Queue <IScsMessage>(); if (mSocket.Connected) { BeginRecieveData(); } return(true); } catch (Exception e) { // Console.WriteLine("connect failed!" + e.Message); Debug.Log("connect failed!" + e.Message); return(false); } }
public bool ConnectServer(string SvrIp, int SvrPort) { String newServIp = ""; AddressFamily newAddressFamily = AddressFamily.InterNetwork; GetIpNetFamilyType(SvrIp, out newServIp, out newAddressFamily); mSocket = new Socket(newAddressFamily, SocketType.Stream, ProtocolType.Tcp); //mSocket.ReceiveTimeout = 500; mSocket.SendTimeout = 500; //设置KeepAlive mSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); mSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); TimeoutObject.Reset(); IPAddress SvrIpAddr = IPAddress.Parse(newServIp); mSocket.BeginConnect(SvrIpAddr, SvrPort, new AsyncCallback(ConnectCallBack), mSocket); if (!TimeoutObject.WaitOne(500, false)) { mSocket.Close(); Debug.Log("Connect Server TimeOut......"); } if (IsConnectSuccess) { //mSocket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null); WireProtocolFactory = new MyWireProtocolFactory(); WireProtocol = WireProtocolFactory.CreateWireProtocol(); WireProtocol.Reset(); msgQueue = new Queue <IScsMessage>(); if (mSocket.Connected) { BeginRecieveData(); } } return(mSocket.Connected); }
/// <summary> /// Connects to server. /// /// </summary> public void Connect() { this.WireProtocol.Reset(); this._communicationChannel = this.CreateCommunicationChannel(); this._communicationChannel.WireProtocol = this.WireProtocol; this._communicationChannel.Disconnected += new EventHandler(this.CommunicationChannel_Disconnected); this._communicationChannel.MessageReceived += new EventHandler<MessageEventArgs>(this.CommunicationChannel_MessageReceived); this._communicationChannel.MessageSent += new EventHandler<MessageEventArgs>(this.CommunicationChannel_MessageSent); this._communicationChannel.Start(); this._pingTimer.Start(); this.OnConnected(); }