ios socket编程初步:iphone客户端与java服务端通信

大家好,这是我的第一个原创教程,下面我们来学习下最基本的SOCKET是怎样在两台电脑上实现数据交换的。
首先是我们的java端:
package com.hcios.socket;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
 
 
 
public class HCNewServer {
 
    /**
     * 1.创建服务器端Socket
     * 
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("欢迎来到Socket的世界");
        ServerSocket serverSocket=null;
         
         
        try {
            serverSocket=new ServerSocket(5678);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
//      input = new InputStreamReader(System.in);
//        bufw = new BufferedReader(input);
//        try {
//            String str =bufw.readLine();
//            bufw2=new BufferedWriter(os);
//            os.print(str);
//           // System.out.print("Show: " + line);
//            bufw2.flush();
//      InputStreamReader input=new InputStreamReader(System.in);
//      BufferedReader br=new BufferedReader(input);
//      
        int i=0;
        while (true)
        {
            Socket thisClient=null;
            try {
                 
                System.out.print("等待客户端连接");
                //接受方法会阻塞主进程
                thisClient= serverSocket.accept();
                System.out.println("有客户端请求socket。同意");
                while (!thisClient.isClosed()){
                    //读取socket的输入流
                    InputStream is=thisClient.getInputStream();
                    InputStreamReader clientInput=new InputStreamReader(is);
                    BufferedReader br=new BufferedReader(clientInput);
                    System.out.println("当前socket客户端的IP地址:"+thisClient.getInetAddress());
                        String clientStr= br.readLine();
                    System.out.println("客户端说:"+clientStr);
                    if (clientStr.equals("goodbye")) {
                        thisClient.close();
                    }
                }
                 
                 
                 
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             
             
             
//          读取Input流过程也会阻塞主进程
             
             
             
            i++;
             
             
             
        }
         
         
         
    }
 
}



然后是我们的客户端(新建一个单视图的工程,需要导入GCDAsyncSoket.h/.m文件和添加相应框架)

controller源代码:
//
//  HCSViewController.m
//  HCSocket
//
//  Created by Reese on 13-8-19.
//  Copyright (c) 2013年 Reese@dctrain. All rights reserved.
//
 
#import "HCSViewController.h"
#import "GCDAsyncSocket.h"
 
@interfaceHCSViewController ()
 
@end
 
@implementationHCSViewController
GCDAsyncSocket *clientSocket;
- (void)viewDidLoad
{
    [superviewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //第一步:初始化Socket
    clientSocket=[[GCDAsyncSocket alloc]initWithDelegate:selfdelegateQueue:dispatch_get_main_queue()];
     
     
     
    //第二步:连接/connect
    NSError*err=nil;
     
    [clientSocket connectToHost:@"localhost"onPort:5678 error:&err];
    if(err) {
        NSLog(@"socket连接函数调用异常:%@",err);
    }
     
     
     
    //第三步:读或者写  I/O
     
     
     
     
    //客户端 读
    //第四步:关闭Socket
     
     
     
     
     
}
 
- (void)didReceiveMemoryWarning
{
    [superdidReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
 
 
#pragma mark  ------GCDAsyncSocket协议--------
//socket连接建立成功委托协议
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString*)host port:(uint16_t)port
{
    NSLog(@"socket连接建立成功,端口号为:%d",port);
}
//socket连接断开委托协议
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError*)err
{
    NSLog(@"socket连接建立失败:%@",err);
}
 
- (void)dealloc {
    [_outputText release];
    [superdealloc];
}
- (IBAction)sendText:(id)sender {
     
     
    //客户端 写
     
    NSString*clientText = [_outputText.text stringByAppendingString:@"\n"];
     
     
    constchar*clientTextData = [clientText cStringUsingEncoding:NSUTF8StringEncoding];
     
    //char dataChar[]="hello,world,I'm a iphone\n";
//    NSString *str=[_outputText.text stringByAppendingString:@"\n"];
     
     
    NSData*data=[NSDatadataWithBytes:clientTextData length:100];
     
    [clientSocket writeData:data withTimeout:1000 tag:1000];
}
@end

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值