using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Runtime.Serialization.Formatters.Binary; using StuMgmLib.MyNameSpace; namespace StuMgmClient { class ClientConnect { //连接 public static Socket Connect(string ip, int port) { Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipAdress = IPAddress.Parse(ip); IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, port); try { client.Connect(ipEndpoint); } catch (Exception ex) { return null; } return client; } //发送并进行序列化 public static void Send(Socket client) { MemoryStream ms = new MemoryStream(); BinaryFormatter iFormatter = new BinaryFormatter(); Info.ClientSend cs = new Info.ClientSend(); cs.account= 1943; cs.password = "1"; iFormatter.Serialize(ms, cs); byte[] buff = ms.GetBuffer(); //发送消息到服务端 client.Send(buff); } //接收并进行反序列化 public static Info.ServerSend Receive(Socket client) { byte[] buffer = new byte[1024 * 1024]; client.Receive(buffer); MemoryStream ms = new MemoryStream(buffer); BinaryFormatter iFormatter = new BinaryFormatter(); Info.ServerSend serverSend = (Info.ServerSend)iFormatter.Deserialize(ms); return serverSend; } } }