当前位置:网站首页>QT client socket qtcpsocket specifies the local IP through bind

QT client socket qtcpsocket specifies the local IP through bind

2022-06-11 00:12:00 Big orange

background :

I do a PC software , It is necessary to control several slave computers at the same time , Use socket communication . But in the production stage, I don't want to always use the computer for debugging , Instead, the communication process is simulated locally .

The local network card can specify multiple ip Address , I want the client to ( Analog slave computer ) Connect server ( Simulate the upper computer ) when , Be able to specify ip And port . So when connecting , To identify which lower computer it is . The lower computer cannot be designed to send a packet to confirm its identity after connecting . At least for now, I don't want the lower computer to make changes , But I do it myself on the upper computer .

Follow the help instructions to use QTcpSocket Class bind Functions can be bound to ip And port , That is to designate . But in fact, once you get to the port , There will be all kinds of discomfort .

When you do not need to identify the client , Don't worry about it. , The client will be based on its own host ip, Automatically select random port . At this time, it is flexible to connect and disconnect casually , Without any influence .

Once bound ip And port , It is not allowed to disconnect and reconnect frequently . Various online methods , Just listen to the socket and don't use it directly QTcpServer, To pass the API call . Or port multiplexing .

In fact, it doesn't apply to me . apply Qt To cross platform , Don't want to try to talk to OS Relevant specific API. Port multiplexing is important for qt In fact, it is not very flexible , Still have to wait OS Response .

resolvent :

Limited to my needs , Just be able to identify the client .

It's simple , Use bind Binding time , Bind only ip That's it , Ports let it be random . There can be several more local network cards ip, Each client specifies one ip, Regardless of port . More efficient .

Be careful :

qt It's a bit of a hole set function , such as setPeerName,setLocalAddress etc. , First of all protect type , You need to write a subclass to call indirectly . Even if it can be called, it will not happen , These functions are only used to set the return value of some functions , It has little significance in practical application . Or it doesn't mean much to my needs .

Often these set Functions can be misleading , No set I will be able to get.

原网站

版权声明
本文为[Big orange]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206102252412720.html