是否可以从服务器连接客户端 [英] Is it possible to connect with client from server

查看:129
本文介绍了是否可以从服务器连接客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#编写TCP客户端服务器软件。我希望客户端在服务器启动后自动与服务器连接。要执行此任务,客户端可能需要知道服务器是否已启动。但是怎么可能呢?



我的情况:同一个局域网上有一个客户端和一个服务器。每个人都知道其他人的IP地址。以下是代码部分,用于连接它们:



服务器端:



I'm writing TCP client server software using C#. I want client be connected with server automatically as soon as server started. To do this task, client may need to know whether the server is started or not. But how, is it possible?

My situation: There is one client and one server on the same LAN network. Each one knows IP address of other one. Here is code section to make connection between them:

Server side:

// Starting the Server ...
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();

...

// Listening for client's connection in a thread ...
while (true)
{
    clientSocket = serverSocket.AcceptTcpClient();
    msg(" The client connected");
}

...





客户方:





Client side:

// Here, client makes connection to the server when user clicks a button
clientSocket.Connect("192.168.1.1", "8888");

...





问候,Orgil.D



Regards, Orgil.D

推荐答案

不,这不是它的完成方式。



想一想。服务器如何知道有客户端要连接?服务器如何找到它们?



不是。
No, this is not how it's done.

Think about it. How is the server going to know that there are clients to connect to? How is the server going to find them??

It's not.


客户端必须设置连接,因为大多数客户端在路由器后面(NAT。)它阻止来自NAT之外的任何人到客户端的传入连接。意味着服务器可通过互联网访问,而客户(主要)则不是。但每隔x分钟进行一次投票应该不会那么糟糕。



祝你好运!
The client has to setup the connection because most clients are behind a router (NAT.) It prevents incoming connections to the client from anyone outside of the NAT. Meaning servers are reachable over the internet and clients are (mostly) not. But polling every x minutes should't be that bad.

Good luck!


我觉得这没什么意义。但是,如果你真的想这样做,你可以让客户端尝试连接循环。
I don't think this makes a lot of sense. However, if you really want to do that, you can just keep the client trying to connect in a loop.


这篇关于是否可以从服务器连接客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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