ios socket和java socket通信 使用GCDAsyncSocket

java端

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static final int PORT = 12345;//监听的端口号 192.168.127.48

  //搭建服务器端
    public static void main(String[] args) throws IOException{
    	Server socketService = new Server();
        //1、a)创建一个服务器端Socket,即SocketService 
        socketService.oneServer();
    }
    @SuppressWarnings("resource")
	public  void oneServer(){
        try{
            ServerSocket server=null;
            try{
                server=new ServerSocket(PORT);
                //b)指定绑定的端口,并监听此端口。
                System.out.println("服务器启动成功");
                //创建一个ServerSocket在端口5209监听客户请求
            }catch(Exception e) {
                    System.out.println("没有启动监听:"+e);
                    //出错,打印出错信息
            }
            Socket socket=null;
            while(true) {
            	 try{
                     socket=server.accept();
//                     String line;
                     BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                     PrintWriter writer=new PrintWriter(socket.getOutputStream());

                     String cStr=in.readLine();
                     System.out.println("Client said:"+cStr);

                         System.out.println("Client 2said:"+cStr);
                         writer.println("server said:"+cStr);
                         writer.flush();

                     //5、关闭资源 
//                     writer.close(); //关闭Socket输出流
//                     in.close(); //关闭Socket输入流
//                     socket.close(); //关闭Socket
//                     server.close(); //关闭ServerSocket
                 }catch(Exception e) {
                     System.out.println("Error11."+e);
                     //出错,打印出错信息
                 }
                 
            }
           
        }catch(Exception e) {//出错,打印出错信息
            System.out.println("Error."+e);
        }
    }
}
ios端


#import "ViewController.h"
#import "GCDAsyncSocket.h"
@interface ViewController ()<GCDAsyncSocketDelegate>

// 客户端socket
@property (strong, nonatomic) GCDAsyncSocket *clientSocket;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];// 1.初始化
    
    CGRect frame = CGRectMake(20, 20, 300, 50);
            UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
           button.frame = frame;
           [button setTitle:@"新添加的动态按钮" forState: UIControlStateNormal];
           button.backgroundColor = [UIColor clearColor];
            button.tag = 2000;
            [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:button];

}
-(IBAction) buttonClicked:(id)sender {
     NSLog(@"点到我");
    if(self.clientSocket){
        [self.clientSocket disconnect];
        self.clientSocket=nil;
    }
    self.clientSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    // 2.链接服务器
    [self.clientSocket connectToHost:@"192.168.198.128" onPort:12345 viaInterface:nil withTimeout:-1 error:nil];
    
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                                            message:@"单击了动态按钮!"
                                                                                           delegate:self
                                                                                  cancelButtonTitle:@"确定"
                                                                                  otherButtonTitles:nil];
//           [alert show];
    
        }

#pragma mark - GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    [self showMessageWithStr:@"链接成功"];
    [self showMessageWithStr:[NSString stringWithFormat:@"服务器IP: %@,%i", host,port]];
//    [self.clientSocket readDataWithTimeout:- 1 tag:0];
    
//    //发消息
    NSData *data = [@"test123\n" dataUsingEncoding:NSUTF8StringEncoding];


    // withTimeout -1 : 无穷大,一直等
    // tag : 消息标记
    [self.clientSocket writeData:data withTimeout:- 1 tag:0];


    [self.clientSocket readDataWithTimeout:- 1 tag:0];
    
    //客户端 写
    
//    NSString *clientText =@"ff\r\n";
//
//
//    const char *clientTextData = [clientText cStringUsingEncoding:NSUTF8StringEncoding];
//
//    //char dataChar[]="hello,world,I'm a iphone\n";
//    //    NSString *str=[_outputText.text stringByAppendingString:@"\n"];
//
//
//    NSData*data=[NSData dataWithBytes:clientTextData length:100];
//
//    [self.clientSocket writeData:data withTimeout:1000 tag:1000];
//    [self.clientSocket readDataWithTimeout:- 1 tag:0];
    
}
//socket连接断开委托协议
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError*)err
{
    NSLog(@"socket连接建立失败:%@",err);
}
// 收到消息
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSString *text = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    [self showMessageWithStr:text];
    [self.clientSocket readDataWithTimeout:- 1 tag:0];
}
// 信息展示
- (void)showMessageWithStr:(NSString *)str {
    NSLog(@"text=%@",str);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}


@end



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值