ios socket AsyncSocket使用

一.项目添加ASyncSocket

  1.下载ASyncSocket库源码

  2.把ASyncSocket库源码加入项目(见附件)

  3.在项目增加CFNetwork框架

 

 

二、具体使用代码如下:

导入:#import "AsyncSocket.h"

 

//发送短消息

-(IBAction)sendString

{

    

   

    NSData *data = [@"test\n" dataUsingEncoding: NSUTF8StringEncoding];

    

    

    static BOOL connectOK = NO

    

    if (!_sendSocket)

    {

        self.sendSocket = [[AsyncSocket alloc] initWithDelegate: self];

        

        NSError *error;

        connectOK = [_sendSocket connectToHost: @"127.0.0.1" onPort: 8000 error: &error];

        

        if (!connectOK)

        {

            [self showAlert:@"连接失败"];

        }else{

            DLog(@"connect success!");

        }

        

        [_sendSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];

    }

    

    if (connectOK)

    {

        [_sendSocket writeData:data withTimeout: -1 tag: 0];

    }

}

 

 

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port

{

DLog(@"%s %d", __FUNCTION__, __LINE__);

    

    [_sendSocket readDataWithTimeout: -1 tag: 0];

}

 

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag

{

    DLog(@"%s %d, tag = %ld", __FUNCTION__, __LINE__, tag);

    

    [_sendSocket readDataWithTimeout: -1 tag: 0];

}

 

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err

{

   DLog(@"%s %d, tag = %@", __FUNCTION__, __LINE__, err);

}

 

// 这里必须要使用流式数据

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag

{

    

    NSString *msg = [[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding];

    

    DLog(@"%s %d, ==读取到从服务端返回的内容=== %@", __FUNCTION__, __LINE__, msg);

    

    [_sendSocket readDataWithTimeout: -1 tag: 0];

}

 

 

- (void)onSocketDidDisconnect:(AsyncSocket *)sock

{

    DLog(@"%s %d", __FUNCTION__, __LINE__);

    

    self.sendSocket = nil;

 

}

 

 

java服务端的代码如下:

 

public class Server {

 

 

    private ServerSocket ss;  

    private Socket socket;  

    private BufferedReader in;  

    private PrintWriter out;  

  

    public Server()   

    {  

        try   

        {  

            ss = new ServerSocket(8000);  

              

            System.out.println("The server is waiting your input...");  

              

            while(true)   

            {  

                socket = ss.accept();  

                  

                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));  

                out = new PrintWriter(socket.getOutputStream(), true);  

                String line = in.readLine();  

                  

                System.out.println("you input is : " + line);  

                                  

                out.println("server back input is :" + line); 

                out.flush();

                  

                out.close();  

                in.close();  

                socket.close();  

                  

                if(line.equals("exit"))  

                    break;  

            }  

              

            ss.close();  

              

        } catch (IOException e) {  

            e.printStackTrace();  

        }  

    }  

  

    public static void main(String[] args)   

    {  

        new Server();  

    }  

 

 

 

}

 

 

注意:向客户端写数据时最后需要加上\n,不然很久都不会得到服务端的返回。

 

上面为普通的socket服务端,最近项目采用apache mina框架建后台的socket服务端,采用上面的asyncSocket一直连接不上服务器,也在网上查询了大量的资料,最终发现需要在写入的数据后面加上0字符才能连接成功,或者采用gzip压缩后再传入服务器。ios的gzip压缩请见下一博客。

 

NSString *requestStrFrmt =  @"发送到服务端数据";

 

 

NSData *requestData = [requestStrFrmt dataUsingEncoding:NSUTF8StringEncoding];

    

    Byte *testByte = (Byte *)[requestData bytes];

    

    Byte bytes[requestData.length+1];

    for(int i=0;i<[requestData length];i++){

        bytes[i]=testByte[i];

    }

    bytes[requestData.length]=0;

    

    

    NSData *adata = [[NSData alloc] initWithBytes:bytes length:requestData.length+1];

 

 

[asyncSocketwriteData:adata withTimeout:-1.0tag:0];

 

这样服务端就能正常的读取到数据并返回了

 

猜你喜欢

转载自zxs19861202.iteye.com/blog/2064736