add to reconnect logic

main
syneffort 2 years ago
parent f01a43d451
commit 4ba3c1a316
  1. 17
      SocketStudy/PComm/PClient.cs

@ -42,12 +42,8 @@ namespace PComm
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.ID = id; this.ID = id;
this.EndPoint = new IPEndPoint(IPAddress.Parse(ip), port); this.EndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
socket.Connect(this.EndPoint);
// send ID Connect();
this.Send(PDataType.ClientID, Encoding.UTF8.GetBytes(this.ID));
socket.BeginReceive(new byte[] { 0 }, 0, 0, 0, AcceptCallback, null);
} }
public PClient(Socket accepted) public PClient(Socket accepted)
@ -57,16 +53,18 @@ namespace PComm
socket = accepted; socket = accepted;
this.EndPoint = (IPEndPoint)socket.RemoteEndPoint; this.EndPoint = (IPEndPoint)socket.RemoteEndPoint;
socket.BeginReceive(new byte[] { 0 }, 0, 0, 0, AcceptCallback, null); socket.BeginReceive(new byte[] { 0 }, 0, 0, 0, AcceptCallback, null);
} }
public void Reconnect() public void Connect()
{ {
if (socket.Connected) if (socket == null || socket.Connected)
return; return;
socket.Connect(this.EndPoint); socket.Connect(this.EndPoint);
// send ID
this.Send(PDataType.ClientID, Encoding.UTF8.GetBytes(this.ID)); this.Send(PDataType.ClientID, Encoding.UTF8.GetBytes(this.ID));
socket.BeginReceive(new byte[] { 0 }, 0, 0, 0, AcceptCallback, null); socket.BeginReceive(new byte[] { 0 }, 0, 0, 0, AcceptCallback, null);
@ -76,6 +74,9 @@ namespace PComm
{ {
try try
{ {
if (!socket.Connected)
Connect();
return socket.Send(buffer, SocketFlags.None); return socket.Send(buffer, SocketFlags.None);
} }
catch (Exception ex) catch (Exception ex)

Loading…
Cancel
Save