您的位置:首页 > 编程语言 > Java开发

ios socket和java socket通信 使用GCDAsyncSocket

2018-01-11 14:07 1056 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: