简体   繁体   English

在Cocoa中运行套接字服务器

[英]Running a Socket Server in Cocoa

I'm trying to write a program that uses sockets to connect with other instances of itself over the network. 我正在尝试编写一个程序,它使用套接字通过网络连接自身的其他实例。 Since eventually I'd like to write a Windows version as well, I'm currently using BSD sockets on the OS X side so that I can ensure that it will be compatible with the (eventual) Windows version. 由于最终我还想编写Windows版本,我目前正在OS X端使用BSD套接字,以便我可以确保它与(最终)Windows版本兼容。

The only way that I've been able to get this to work so far is if I specify my actual IP address when creating the server socket. 到目前为止,我能够使这个工作的唯一方法是在创建服务器套接字时指定我的实际IP地址。 If I use 127.0.0.1 instead, then I can only connect from my local machine. 如果我改用127.0.0.1,那么我只能从本地机器连接。

While this is fine in theory, the question them becomes how do I know which IP address to use? 虽然这在理论上很好,但问题是我如何知道使用哪个IP地址? I'm not sure how to get an IP address for the current machine via Cocoa, and even if I can, what if there are multiple valid IP address (such as both an Airport and ethernet connections, for example). 我不知道如何通过Cocoa获取当前机器的IP地址,即使我可以,如果有多个有效的IP地址(例如机场和以太网连接),该怎么办。 How do I know which one to use? 我怎么知道使用哪一个? I could ask the user, but that doesn't seem like something they could/should know. 我可以问用户,但这似乎不是他们可以/应该知道的事情。

I can provide my client and server connection code if necessary, however given that I am able to make a connection from a remote machine, I'm thinking that the problem isn't in my code. 如果需要,我可以提供我的客户端和服务器连接代码,但是考虑到我能够从远程计算机建立连接,我认为问题不在我的代码中。

Thank you for your time. 感谢您的时间。 :) :)

Use 0.0.0.0 as the IP address to listen on. 使用0.0.0.0作为要侦听的IP地址。 It'll listen on all addresses. 它会听取所有地址。

Probably, a constant is defined for this address in the socket API you are using. 可能在您正在使用的套接字API中为此地址定义了一个常量。 If you are using standard C sockets API, it's INADDR_ANY. 如果您使用的是标准C套接字API,那么它就是INADDR_ANY。

There is a network discoverability protocol called Bonjour that you can use to publish your servers on the network and then your clients can automatically connect to them. 有一个名为Bonjour的网络可发现性协议,您可以使用该协议在网络上发布服务器,然后您的客户端可以自动连接到它们。 It's cross platform, but usually called zero-config on other systems. 它是跨平台的,但通常在其他系统上称为零配置。

When doing any kind of socket programming checkout Beej's socket guide. 在做任何类型的套接字编程时,检查Beej的套接字指南。 Its been around for ages and covers most of the basics. 它已存在多年,涵盖了大部分基础知识。

http://beej.us/guide/bgnet/ http://beej.us/guide/bgnet/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM