Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

55 wiersze
1.6 KiB

  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Runtime.Serialization.Formatters.Binary;
  6. using StuMgmLib.MyNameSpace;
  7. namespace StuMgmClient
  8. {
  9. class ClientConnect
  10. {
  11. //连接
  12. public static Socket Connect(string ip, int port)
  13. {
  14. Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  15. IPAddress ipAdress = IPAddress.Parse(ip);
  16. IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, port);
  17. try
  18. {
  19. client.Connect(ipEndpoint);
  20. }
  21. catch (Exception ex)
  22. {
  23. return null;
  24. }
  25. return client;
  26. }
  27. //发送并进行序列化
  28. public static void Send(Socket client)
  29. {
  30. MemoryStream ms = new MemoryStream();
  31. BinaryFormatter iFormatter = new BinaryFormatter();
  32. Info.ClientSend cs = new Info.ClientSend();
  33. cs.account= 1943;
  34. cs.password = "1";
  35. iFormatter.Serialize(ms, cs);
  36. byte[] buff = ms.GetBuffer();
  37. //发送消息到服务端
  38. client.Send(buff);
  39. }
  40. //接收并进行反序列化
  41. public static Info.ServerSend Receive(Socket client)
  42. {
  43. byte[] buffer = new byte[1024 * 1024];
  44. client.Receive(buffer);
  45. MemoryStream ms = new MemoryStream(buffer);
  46. BinaryFormatter iFormatter = new BinaryFormatter();
  47. Info.ServerSend serverSend = (Info.ServerSend)iFormatter.Deserialize(ms);
  48. return serverSend;
  49. }
  50. }
  51. }