简体   繁体   English

如何使用GKSession从服务器向客户端发送请求?

[英]How to send request from server to client using GKSession?

I want to know how can I send request from server to client using GKSession? 我想知道如何使用GKSession从服务器向客户端发送请求? The reference class for GKSession say the following: GKSession的参考类说明以下内容:

- (void)connectToPeer:(NSString *)peerID withTimeout:(NSTimeInterval)timeout Parameters peerID The string that

identifies the peer to connect to. 标识要连接的对等体。

timeout The amount of time to wait before canceling the connection attempt. 超时取消连接尝试之前要等待的时间。

Discussion 讨论区

When your application is acting as a client, it calls this method to connect to an available peer it discovered. 当您的应用程序充当客户端时,它将调用此方法以连接到发现的可用对等方。 When your application calls this method, a request is transmitted to the remote peer, who chooses whether to accept or reject the connection request. 当您的应用程序调用此方法时,请求将传输到远程对等方,后者选择是接受还是拒绝连接请求。

What should I use if I am server? 如果我是服务器,应该使用什么?

作为服务器,您可以通过以下方式进行客户端连接

peer2peerSession.available = YES;

Here is an example of creating a GKSession instance as a server: 这是将GKSession实例创建为服务器的示例:

[[GKSession alloc] initWithSessionID:sessionID displayName:@"Chris" sessionMode : GKSessionModeServer];

Here is an example of how to create a GKSession as a client: 这是一个如何创建GKSession作为客户端的示例:

[[GKSession alloc] initWithSessionID:sessionID displayName:@"Angel" sessionMode : GKSessionModeClient];

GKSessionModePeer will create a GKSession instance that will both advertise itself as a server, and at the same time look for advertising servers (in other words act as a client searching for servers). GKSessionModePeer将创建一个GKSession实例,该实例将自己作为服务器进行广告,同时查找广告服务器(换句话说,充当搜索服务器的客户端)。

You then need to set a delegate for your GKSession object, after-which the delegate needs to implement the following delegate method: 然后,您需要为GKSession对象设置一个委托,此后该委托需要实现以下委托方法:

- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState : (GKPeerConnectionState)state

Within the above method you will receive messages from the session that a device has become available, became unavailable, connected, etc. 在上述方法中,您将从会话中接收到有关设备已变得可用,变得不可用,已连接等的消息。

To send a request: 发送请求:

[_session connectToPeer:peerID withTimeout:_session.disconnectTimeout];

To accept a request: 接受请求:

[_session acceptConnectionFromPeer:peerID error:&error];

There is a lot of code involved and the best tutorial for you to understand everything is located here: Simple Card Playing game using GKSession 这里涉及很多代码,并且您可以了解所有内容的最佳教程位于: 使用GKSession的简单纸牌游戏

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

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