iOS中的socket通信

来源:互联网 发布:21级研究所升级数据 编辑:程序博客网 时间:2024/06/05 06:37

iOS中的socket通信,用到了AsyncSocket开源的框架,不错,挺好用的。

OC: (Client)

- (void) connectButtonPressed {

    

    if (!asyncSocket) {

        

        asyncSocket = [[AsyncSocket allocinitWithDelegate:self];

        NSError *err = nil;

        

        if(![asyncSocket connectToHost:@"192.168.1.103" onPort:25001withTimeout:10 error:&err]) {

            

            NSLog(@"Error: %@", err);

            

        }

    }

    

}



- (void) sendButtonPressed {

    


    NSData* aData= [inputTextView.text dataUsingEncodingNSUTF8StringEncoding];

    

    [asyncSocket writeData:aData withTimeout:-1 tag:1];

    

}


-(void)ontime{

    

    [asyncSocket readDataWithTimeout:-1 tag:0];

    

}



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

{

    NSLog(@"onSocket:%p didConnectToHost:%@ port:%hu", sock, host, port);

    

    //Add timer.

    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:selfselector:@selector(ontime) userInfo:nil repeats:YES];

}


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

{

    NSString* aStr = [[NSString allocinitWithData:dataencoding:NSUTF8StringEncoding];

    messageTextView.text =[NSString stringWithFormat:@"%@ \n Server: %@",messageTextView.text, aStr];;

    

    [aStr release];


}


- (void)onSocket:(AsyncSocket *)sock didSecure:(BOOL)flag

{

    NSLog(@"onSocket:%p didSecure:YES", sock);

}


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

{

    NSLog(@"onSocket:%p willDisconnectWithError:%@", sock, err);

    

    [timer invalidate];

    timer = nil;

    

}


- (void)onSocketDidDisconnect:(AsyncSocket *)sock

{

    //断开连接了

    NSLog(@"onSocketDidDisconnect:%p", sock);

}


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


{

    

    NSLog(@"thread(%@),onSocket:%p didWriteDataWithTag:%ld",[[NSThreadcurrentThreadname],sock, tag);


}


C#: (Server) 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;


namespace SocketServer
{
    public partial class Form1 : Form
    {

        private IPAddress clientIP = IPAddress.Parse("192.168.1.103");//以本机作测试
        private IPEndPoint serverfulladdr;//完整终端地址
        private Socket sock;
        private System.Timers.Timer mytimer;
        private ArrayList alsock;//当建立了多个连接时用于保存连接


        public Form1()
        {
            InitializeComponent();
        }

        private void btstart_Click(object sender, EventArgs e)
        {

            serverfulladdr = new IPEndPoint(clientIP, 25001);//取端口号1000

            //构造socket对象,套接字类型为“流套接字”,指定五元组中的协议元

            sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //指定五元组中的本地二元,即本地主机地址和端口号

            sock.Bind(serverfulladdr);

            //监听是否有连接传入,指定挂起的连接队列的最大值为20

            sock.Listen(20);

            alsock = new ArrayList();

            //构造定时器,时间间隙为1秒,即每隔一秒执行一次accept()方法,以获取连接请求队列中//第一个挂起的连接请求
            mytimer = new System.Timers.Timer(1000);

            mytimer.Elapsed += new System.Timers.ElapsedEventHandler(mytimer_elapsed);

            mytimer.Enabled = true;

        }

 

        private void mytimer_elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

            mytimer.Enabled = false;

            //执行accept(),当挂起队列为空时将阻塞本线程,同时由于上一语句,定时器将停止,直//至有连接传入

            Socket acceptsock = sock.Accept();

            //将accept()产生的socket对象存入arraylist

            alsock.Add(acceptsock);

            // 构造threading.timer对象,这将导致程序另启线程。线程将执行回调函数,该委托限制//函数参数须为object型。threading.timer构造器的第二个参数即传入回调函数的参数;第//三个参数指定调用回调函数之前的延时,取0则立即启动;最后一个参数指定调用回调函数//的时间间隔,取0则只执行一次。

            System.Threading.Timer ti = new System.Threading.Timer(new System.Threading.TimerCallback(receivemsg), acceptsock, 0, 0);

            mytimer.Enabled = true;

        }

 

        private void receivemsg(object obj)
        {

            Socket acceptsock = (Socket)obj;

            try
            {

                while (true)
                {

                    byte[] bytearray = new byte[100];

                    acceptsock.Receive(bytearray);//接收数据

                    //将字节数组转成字符串

                    string strrec = System.Text.Encoding.UTF8.GetString(bytearray);

                    if (this.rtbreceive.InvokeRequired)
                    {

                        this.rtbreceive.Invoke(new EventHandler(this.changericktextbox), new object[] { strrec, EventArgs.Empty });

                    }

                }

            }

            catch (Exception ex)
            {

                acceptsock.Close();

                MessageBox.Show("s:receive message error" + ex.Message);

            }

        }

 

        private void changericktextbox(object obj, EventArgs e)
        {

            string s = System.Convert.ToString(obj);

            this.rtbreceive.AppendText(s + Environment.NewLine);

        }


        private void btsend_Click(object sender, EventArgs e)
        {

            Socket sc = null;

            byte[] bytesend = System.Text.Encoding.UTF8.GetBytes(this.txtinput.Text.ToCharArray());

            try
            {

                //同时存在若干个客户端连接时,需要确定是哪个连接,因为我的调试都是一个连接,所以直接用0

                sc = (Socket)alsock[0];

                //发送数据

                sc.Send(bytesend);

            }

            catch (Exception ex)
            {

                if (sc != null)
                {
                    sc.Close();
                }

                MessageBox.Show("s:send message error" + ex.Message);
            }
        }


        private void btclose_Click(object sender, EventArgs e)
        {

            try
            {
                Application.Exit();
            }

            catch (Exception ex)
            {
                MessageBox.Show("s:close socket error" + ex.Message);
            }

        }

    }
}

0 0
原创粉丝点击