日期:2014-05-17 浏览次数:20962 次
服务端: private void button1_Click(object sender, EventArgs e) { IPAddress ip = IPAddress.Parse("127.0.0.1"); IPEndPoint ipep = new IPEndPoint(ip, 55555); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.Bind(ipep); server.Listen(10); while (true) { Socket s = server.Accept(); byte[] uspw = new Byte[1024]; //接受 然后反序列化 s.Receive(uspw); BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(uspw); user us= (user)formatter.Deserialize(stream); } } [Serializable] public class user { public string userID; public string password; }
客户端: private void button1_Click(object sender, EventArgs e) { Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(IPAddress.Parse("127.0.0.1"), 55555); MemoryStream stream = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); user us = new user(); us.userID = "xiao"; us.password = "rrr"; formatter.Serialize(stream, us); stream.Flush(); byte[] uspw = stream.ToArray(); client.Send(uspw); } [Serializable] public class user { public string userID; public string password; }