socket 简单demo

来源:互联网 发布:js array 长度 编辑:程序博客网 时间:2024/06/07 09:31



服务端代码;  


public class SocketService {     public static void main(String[] args) {        try{    //为了简单起见,所有的异常信息都往外抛              int port = 8899;              //定义一个ServerSocket监听在端口8899上              ServerSocket server = new ServerSocket(port);              //server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的              Socket socket = server.accept();              //跟客户端建立好连接之后,我们就可以获取socket的InputStream,并从中读取客户端发过来的信息了。              Reader reader = new InputStreamReader(socket.getInputStream());              char chars[] = new char[64];              int len;              StringBuilder sb = new StringBuilder();              String temp;                              temp = new String(chars, 0, reader.read(chars));                 sb.append(temp);                 System.out.println("from client:------> " + sb);                           //读完后写一句              Writer writer = new OutputStreamWriter(socket.getOutputStream());              writer.write("Hello Client.--------->麦子");              writer.flush();              writer.close();              reader.close();              socket.close();              server.close();             }catch(Exception e){         e.printStackTrace();    }       }}

OC端代码如下:



#import "ViewController.h"@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,NSStreamDelegate,UITextFieldDelegate>@property (weak, nonatomic) IBOutlet UITableView *tableView;@property (nonatomic,strong) NSMutableArray *msgArray; // 对话数据// OC 输入输出流@property (nonatomic,strong) NSInputStream *inputStream;@property (nonatomic,strong) NSOutputStream *outputStream;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    _msgArray = [[NSMutableArray alloc]init];    for (int  i = 0; i < 10; i++) {        [_msgArray addObject:@"测试数据--->"];    }    _tableView.dataSource = self;    _tableView.delegate = self;    [self connectionAction];}- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{       return 1;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{       return _msgArray.count;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];     tableView.separatorStyle = UITableViewCellSeparatorStyleNone;    UIView  *view = cell.contentView;    UILabel *label = [view viewWithTag:10];    label.text = [_msgArray objectAtIndex:indexPath.row];        return cell;}- (void)connectionAction{        NSLog(@"建立连接........");            NSString *host = @"192.168.155.2";    int port = 8899;        // 定义C语言输入输出流    CFReadStreamRef  readStream;    CFWriteStreamRef writeStream;    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream);        // C语言对象输入输出流转成OC对象    _inputStream = (__bridge NSInputStream *)(readStream);    _outputStream = (__bridge NSOutputStream *)(writeStream);        // 设置代理    _inputStream.delegate = self;    _outputStream.delegate = self;        // 添加主运行循环    [_inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];        [_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];        //打开输入输出流    [_inputStream open];    [_outputStream open];    }#pragma mark   NSStreamDelegate- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{    NSLog(@"%@",[NSThread currentThread].description);        switch (eventCode) {        case NSStreamEventOpenCompleted:                        NSLog(@"输入输出流打开完成");                        break;                    case NSStreamEventHasBytesAvailable:                        NSLog(@"有字节可以读");                        [self readData];                        break;                    case NSStreamEventHasSpaceAvailable:                        NSLog(@"可以发送字节");                        break;                    case NSStreamEventErrorOccurred:                    NSLog(@"连接出现错误");                        break;                    case NSStreamEventEndEncountered:                        NSLog(@"连接结束");                        // 关闭输入输出流                        [_inputStream close];            [_outputStream close];                        //从主运行循环移除                        [_inputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];            [_outputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];                        break;                    default:            break;    }}#pragma mark     发送数据- (void)sendData{    NSString *msg = @"我是客户端数据.....";        NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];        [_outputStream write:data.bytes maxLength:data.length];}#pragma mark     读取数据- (void)readData{    // 缓存区域 1024    uint8_t buf[1024];        // 返回实际装的字节数    NSInteger len = [_inputStream read:buf maxLength:sizeof(buf)];        // 把字节数转成字符串    NSData *data = [NSData dataWithBytes:buf length:len];        // 从服务器返回的字符    NSString *msg = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];        if (msg != nil && msg.length > 0) {                NSLog(@"服务器返回的字符串---->%@",msg);                //  刷新TableView        [_msgArray addObject:msg];        [_tableView reloadData];                NSIndexPath *lastPath = [NSIndexPath indexPathForRow:_msgArray.count - 1 inSection:0];        [_tableView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:true];    }}- (IBAction)readAction:(id)sender {     }- (IBAction)sendAction:(id)sender {        [self sendData];    }@end







0 0