using System; using System.Diagnostics; using System.Net; using System.Net.Sockets; namespace StuMgmClient { class Comm { #region 基本函数 const int bufSize = 1024 * 1024; static IPEndPoint m_ipEndpoint; static Socket m_socket; static byte[] m_buf; void Init(string ip,int port) { IPAddress ipAdress = IPAddress.Parse(ip); m_ipEndpoint = new IPEndPoint(ipAdress, port); m_buf = new byte[bufSize]; } void Connect() { try { m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_socket.Connect(m_ipEndpoint); } catch (Exception ex) { Debug.Print(ex.Message); } } bool Send(byte[] data) { try { m_socket.Send(data); return true; } catch(Exception e) { Debug.Print(e.Message); return false; } } bool Receive() { try { Array.Clear(m_buf, 0, m_buf.Length); m_socket.Receive(m_buf); return true; } catch (Exception e) { Debug.Print(e.Message); return false; } } void DisConnect() { client.Close(); } #endregion internal ErrCode VerifLogin(string userName,string pawssword,out Roles role) { role = Roles.Error; Connect(); UserInfo cs = new UserInfo(userName,pawssword); byte[] sendBuf; if(Utility.BinSerialize(cs,out sendBuf )) return ErrCode.FailSerial; if (Send(sendBuf)) return ErrCode.FailSend; if (Receive()) return ErrCode.FailReceive; object o; if (Utility.BinDeserialize(m_buf, out o)) return ErrCode.FailDeserial; if (!(o is UserInfo)) return ErrCode.ErrData; DisConnect(); role = ((UserInfo)o).UserRole; return ErrCode.Success; } } }