gpt4 book ai didi

通过套接字的 iOS Hello World

转载 作者:可可西里 更新时间:2023-11-01 05:38:42 24 4
gpt4 key购买 nike

我需要在 iOS 应用程序和我的 Java 套接字服务器之间实现简单的套接字通信(字符串)。我设法将两者连接起来,但我无法发送任何消息。 Java 服务器几乎取自此 example ,这是我建立连接并(尝试)向服务器发送消息的代码的一部分:

- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.10", 2004, &readStream, &writeStream);
self.inputStream = objc_unretainedObject(readStream);
self.outputStream = objc_unretainedObject(writeStream);
[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];
[self.outputStream open];
}

- (void)sendMessage {
NSString *response = [NSString stringWithFormat:@"aaa"];
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[self.outputStream write:[data bytes] maxLength:[data length]];
}

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

NSLog(@"stream event %i", streamEvent);

switch (streamEvent) {

case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
break;
case NSStreamEventHasBytesAvailable:

if (theStream == self.inputStream) {

uint8_t buffer[1024];
int len;

while ([self.inputStream hasBytesAvailable]) {
len = [self.inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {

NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

if (nil != output) {

NSLog(@"server said: %@", output);
//[self messageReceived:output];

}
}
}
}
break;


case NSStreamEventErrorOccurred:

NSLog(@"Can not connect to the host!");
break;

case NSStreamEventEndEncountered:

[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
theStream = nil;

break;
default:
NSLog(@"Unknown event");
}

}
- (IBAction)loginButtonClicked {
[self initNetworkCommunication];
[self sendMessage];
...}

最佳答案

来不及回复了..希望这可以帮助某人......

要通过套接字发送字符串,您必须标记字符串的结尾。 IE;添加一个\n

对于上面的例子:

方法:sendMessage

NSString *response  = [NSString stringWithFormat:@"aaa\n"];

关于通过套接字的 iOS Hello World,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8307431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com