我有一个作为服务器运行的.NET桌面程序,我正在尝试在iOS中实现我的客户端程序的端口,但是我从NSSocket获得了一些奇怪的行为。这是服务器的相关代码。
public NetworkListener()
{
_Stream = new MemoryStream();
_tcpServer = new TcpListener(System.Net.IPAddress.Any, 8086);
_endPoints = new List<EndPoint>();
}
public void BeginListening()
{
_tcpServer.Start();
_workerThread = new Thread(new ThreadStart(WorkerLoop));
_workerThread.IsBackground = true;
_workerThread.Start();
}
private void WorkerLoop()
{
while(true)
{
_clientSocket = _tcpServer.AcceptSocket();
_networkStream = new NetworkStream(_clientSocket, true);
/* ... rest of method here ... */
}
}
我在iOSSimulator中使用XCode 4.2并以iOS 5为目标尝试以下代码。托管模拟器的Mac与服务器程序位于同一网络上,我可以运行使用相同硬编码本地IP的Java客户端如下连接就好了。在Objective C代码中,我收到一些数据并将其存储在NSData成员属性中,然后打开Socket后,我使用流回调告诉我何时尝试发送数据。
- (IBAction)connectToServer
{
NSURL *serverUrl = [NSURL URLWithString:@"10.0.0.5"];
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)[serverUrl host], 8086, &readStream, &writeStream);
[self setInStream:(NSInputStream *)readStream];
[self setOutStream:(NSOutputStream *)writeStream];
[self.inStream setDelegate:self];
[self.outStream setDelegate:self];
[self.inStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inStream open];
[self.outStream open];
NSError *error = [self.outStream streamError];
if (error) {
NSLog(@"outstream error: %@", [error localizedDescription]);
}
}
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
NSError *error;
if ([aStream isEqual:outStream]) {
switch (eventCode) {
case NSStreamEventHasSpaceAvailable:
NSLog(@"Stream has space!");
[self writeDataToStream];
break;
case NSStreamEventOpenCompleted:
NSLog(@"Stream is open!");
break;
case NSStreamEventErrorOccurred:
error = [self.outStream streamError];
NSLog(@"Stream error occured: %@", [error localizedDescription]);
break;
default:
break;
}
}
}
- (void)writeDataToStream
{
unsigned int byteIndex = 0;
unsigned int length = data.length;
uint8_t *buffer = (uint8_t *)[data bytes];
while (byteIndex <= length) {
unsigned int bufferLength = (length - byteIndex >= 1024) ? 1024 : (length - byteIndex);
uint8_t tempBuffer[bufferLength];
(void)memcpy(tempBuffer, buffer, bufferLength);
if (self.outStream.hasSpaceAvailable) {
bufferLength = [self.outStream write:tempBuffer maxLength:bufferLength];
byteIndex += bufferLength;
} else
NSLog(@"Stream is blocked!");
}
}
在XCode控制台中,我看到“Stream is open!”,然后是“Stream has space!”,然后是一个异常,上面写着“操作无法完成。错误的文件描述符”。我在_tcpServer.AcceptSocket()
之后立即在我的服务器代码中放置了一个断点,但它从未命中过。似乎流打开了,但套接字永远不会连接?
答案 0 :(得分:-1)
尝试检查[serverUrl host]是否为nil。
我也遇到了这个问题,所以我所做的是在IP地址(http://
)之前添加URLWithString:@"http://10.0.0.5"
协议字符串。