在用TCP连接两台PC时遇到问题 [英] have a problem to connect two pc with TCP

查看:51
本文介绍了在用TCP连接两台PC时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个程序在同一网络的不同PC上运行
当我使用UDP时,它们工作正常,但是当我使用TCP时,客户端无法与服务器建立连接,我无法弄清为什么

TCP服务器

i have two program running on different pc on the same network
when i use UDP they work fine but when i used TCP the client fail to make connection with the server and i can''t figured why

TCP SERVER

public delegate object ClientConnectHandler(Socket datasocket);
   public delegate void DataReceivedHandler(object obj,byte[] data);
   public delegate void ClientDisconnectHandler(object obj);
   public class TCPServer
   {
       public event ClientConnectHandler WhenClientConnect;
       public event DataReceivedHandler WhenDataReceived;
       public event ClientDisconnectHandler WhenClientDisconnect;
       Socket ConnectionSocket;
       IPEndPoint Endpoint;
       byte[] Data=new byte[10000];
       object obj=new object();
       List<Socket> OnlineClients = new List<Socket>();
       public TCPServer()
       {
           ConnectionSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
           Endpoint = new IPEndPoint(IPAddress.Parse(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString()),6666);
       }
       public TCPServer(string ip, int port)
       {
           ConnectionSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
           Endpoint = new IPEndPoint(IPAddress.Parse(ip), port);
       }
       public void Listen()
       {
           ConnectionSocket.Bind(Endpoint);
           ConnectionSocket.Listen(100);
           ConnectionSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
       }
       public void OnClientConnect(IAsyncResult result)
       {
           Socket s = ConnectionSocket.EndAccept(result);
           OnlineClients.Add(s);
           if (WhenClientConnect != null)
               obj = WhenClientConnect(s);
           ConnectionSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
           s.BeginReceive(Data, 0, Data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), new SSocket {  Object=obj , Socket=s});
       }
       public void OnDataReceived(IAsyncResult result)
       {
           SSocket ssocket = (SSocket)result.AsyncState;
           try
           {
               int size = ssocket.Socket.EndReceive(result);
               if (WhenDataReceived != null)
                   WhenDataReceived(ssocket.Object, Data.Take(size).ToArray());
               Data = new byte[10000];
               ssocket.Socket.BeginReceive(Data, 0, Data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), new SSocket { Object = obj, Socket = ssocket.Socket });
           }
           catch(SocketException ex)
           {
               if(ex.ErrorCode == 10054)
               {
                   foreach (Socket item in OnlineClients)
                       if (ssocket.Socket == item)
                           OnlineClients.Remove(item);
                   if (WhenClientDisconnect != null)
                       WhenClientDisconnect(ssocket.Object);
               }
           }
       }
       public void Send(Socket socket,byte[] data)
       {
           if(socket!=null)
               socket.Send(data);
       }
   }
   public class SSocket
   {
       object obj;
       public object Object
       {
           get { return obj; }
           set { obj = value; }
       }
       Socket socket;
       public Socket Socket
       {
           get { return socket; }
           set { socket = value; }
       }
   }



TCP客户端



TCP CLIENT

public class TCPClient
 {
     byte[] data = new byte[10000];
     Socket socket;
     Action<string> action;
     public Socket TCPSocket
     {
         get { return socket; }
     }
     public TCPClient(Action<string> action)
     {
         this.action = action;
     }
     public void Connect(string ipAddress, int port)
     {
         try
         {
             socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
             socket.Connect(ipEndPoint);
             if (socket.Connected)
                 WaitForData();
         }
         catch (SocketException se)
         {
             MessageBox.Show("connection faild," + se.Message);
         }
     }
     private void WaitForData()
     {
         try
         {
             socket.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
         }
         catch (SocketException se)
         {
             MessageBox.Show(se.Message);
         }
     }
     private void OnDataReceived(IAsyncResult asyn)
     {
         try
         {
             action(StringConverter.ToString(data));
             WaitForData();
         }
         catch (SocketException se)
         {
             MessageBox.Show(se.Message);
         }
     }
     public void Send(string message)
     {
         try
         {
             socket.Send(StringConverter.ToByteArray(message));
         }
         catch (ArgumentNullException ex)
         { MessageBox.Show("You have to connect to the server first"); }
         catch (SocketException se)
         { MessageBox.Show(se.Message); }
     }
     public void Close()
     {
         socket.Close();
     }
 }







can any one help please

推荐答案

使用WCF更为简单,而且所涉及的代码也更少.

关于您的问题,请确保两台计算机都使用相同的端口进行通讯.另请注意,如果当前正在使用端口,则在该框中运行的应用程序将引发异常.当应用崩溃时,您可能会无意间将端口保持打开状态. WCF为您处理所有这些挑剔的事情.
Using WCF is much simpler, and there''s a lot less code involved.

As to your question, make sure that both machines are using the same port for comms. Also be aware that if a port is currently in use, the app running on that box will throw an exception. You could inadvertantly be leaving a port open when the app crashes. WCF handles all this nitpicky stuff for you.


这篇关于在用TCP连接两台PC时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆