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