Server
(不需要制定IP)
但是需要指定端口
#import <Cocoa/Cocoa.h>
#import "AsyncSocket.h"
@interface AppDelegate :NSObject <NSApplicationDelegate>
{
AsyncSocket *_listenSocket;
}
@end
//开启监听
_listenSocket = [[AsyncSocketalloc] initWithDelegate: self];
//监听
if([_listenSocketacceptOnPort:12345error:nil])
{
[textViewsetText:@"服务开启\n"];
}
- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket
{
//socket保存引用 或者再顶一个 socket来保存它
[socketArrayaddObject:newSocket];
//接受消息
[sock readDataWithTimeout: -1tag: 0];
}
====================================================
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
// NSLog(@"%s %d", __FUNCTION__, __LINE__);
NSString *welcomeMsg =@"welcome to Server\r\n";
NSData *welcomeData = [welcomeMsgdataUsingEncoding:NSUTF8StringEncoding];
[sockwriteData:welcomeData withTimeout:-1 tag:0];
[sock readDataWithTimeout: -1tag: 0];
}
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
// NSLog(@"%s %d, tag = %ld", __FUNCTION__, __LINE__, tag);
//接收消息
[sock readDataWithTimeout: -1tag: 0];
}
// 这里必须要使用流式数据
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString *msg = [[[NSStringalloc] initWithData: dataencoding:NSUTF8StringEncoding]autorelease];
// NSLog(@"%s %d, msg = %@", __FUNCTION__, __LINE__, msg);
NSString *str = [NSStringstringWithFormat:@"receive:%@\n%@",msg,textView.text];
[textViewsetText:str];
[sock readDataWithTimeout: -1tag: 0];
}
AsyncSocket *_sendSocket;
.m
#define SERVER_IP @"192.168.11.64"
//#define SERVER_IP @"127.0.0.1"
#define SERVER_PORT 54321
//连接到服务器
_sendSocket = [[[AsyncSocketalloc] initWithDelegate: self] autorelease];
NSError *error;
connectOK = [_sendSocketconnectToHost: SERVER_IPonPort: SERVER_PORTerror: &error];
if (!connectOK)
{
NSLog(@"connect error: %@", error);
}
else
{
NSLog(@"connected");
}
// 这里必须要使用流式数据
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString *msg = [[[NSStringalloc] initWithData: dataencoding:NSUTF8StringEncoding]autorelease];
// NSLog(@"%s %d, msg = %@", __FUNCTION__, __LINE__, msg);
NSString *str = [NSStringstringWithFormat:@"收到:%@\n%@",msg,textView.text];
[textViewsetText:str];
[sock readDataWithTimeout: -1tag: 0];
}
发消息
NSString *welcomeMsg =@"welcome to Server\r\n";
NSData *welcomeData = [welcomeMsgdataUsingEncoding:NSUTF8StringEncoding];
[sockwriteData:welcomeData withTimeout:-1 tag:0];
发完消息后要及时接收消息
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
// NSLog(@"%s %d, tag = %ld", __FUNCTION__, __LINE__, tag);
//及时接受
[sock readDataWithTimeout: -1tag: 0];
}
接受消息
NSString *msg = [[[NSStringalloc] initWithData: dataencoding:NSUTF8StringEncoding]autorelease];
// NSLog(@"%s %d, msg = %@", __FUNCTION__, __LINE__, msg);
NSString *str = [NSStringstringWithFormat:@"收到:%@\n%@",msg,textView.text];