iOS socket 筆記

來源:互聯網
上載者:User

標籤:winform   style   blog   http   ar   io   os   使用   sp   

ios 客服端:

下載 AsyncSocket 開發架構,拖到項目中

//建立

#import "ViewController.h"

#import <sys/socket.h>

#import <netinet/in.h>

#import <arpa/inet.h>

#import <unistd.h>

#import "AsyncSocket.h"

#define DEVW [[UIScreen mainScreen]bounds].size.width

@interface ViewController ()

{

    AsyncSocket *asysocket;

    

}

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

   asysocket = [[AsyncSocket alloc] initWithDelegate:self];

    

    NSError *err = nil;

    

       if(! [self SocketOpen:@"172.16.1.92" port:1212])

        

    {

        

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

        

    }

    

    

   

    // Do any additional setup after loading the view, typically from a nib.

}

-(void)sendData:(UIButton *)click

{

    NSMutableString *sendString=[NSMutableString stringWithCapacity:1000];

    

    [sendString appendString:@"hello world!"];

    

    NSData *cmdData = [sendString dataUsingEncoding:NSUTF8StringEncoding];

    

    [asysocket writeData:cmdData withTimeout:-1 tag:0];

    

       

 

 

}

 

//開啟

- (NSInteger)SocketOpen:(NSString*)addr port:(NSInteger)port

{

    if (![asysocket isConnected])

    {

        [asysocket connectToHost:addr onPort:port withTimeout:-1 error:nil];

        

        //NSLog(@"connect to Host:%@ Port:%d",addr,port);

    }

    return 0;

}

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

{

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

}

 

- (void)onSocketDidDisconnect:(AsyncSocket *)sock

{

    NSLog(@"onSocketDidDisconnect");

}

 

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

{

    

    NSLog(@"didConnectToHost");

    

    //這是非同步返回的串連成功,

    

    [sock readDataWithTimeout:-1 tag:0];

}

 

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

{

    

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

   

    if(msg)

    {

        //處理受到的資料

        NSLog(@"收到的資料:%@",msg);

    }

    else

    {

        

        NSLog(@"Error converting received data into UTF-8 String");

        

    }

    

    NSString *[email protected]"串連成功";

    

    NSData *cmdData = [message dataUsingEncoding:NSUTF8StringEncoding];

    

    [sock writeData:cmdData withTimeout:-1 tag:0];

    

    [sock readDataWithTimeout:-1 tag:0];

}

 

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

{

    NSLog(@"didWriteDataWithTag:%ld",tag);

    [sock readDataWithTimeout:-1 tag:0];

}

 

 

c#服務端:

//伺服器端using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Net.Sockets;using System.Net;using System.Threading;namespace Server{    public partial class Form1 : Form    {        Socket socketSend;        public Form1()        {            InitializeComponent();            CheckForIllegalCrossThreadCalls = false;        }        //監聽        private void button1_Click(object sender, EventArgs e)        {            Socket socketWatch = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);            IPAddress ip = IPAddress.Any;            IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.txtPort.Text));            socketWatch.Bind(point);            ShowMsg("監聽成功");            //監聽            socketWatch.Listen(10);            //使用線程不斷監聽            Thread thread = new Thread(Listen);            thread.IsBackground = true;            thread.Start(socketWatch);        }        //發送資訊        private void button2_Click(object sender, EventArgs e)        {            string msg = this.txtMsg.Text.Trim();            byte[] buffer = Encoding.UTF8.GetBytes(msg);            socketSend.Send(buffer);        }                //監聽用戶端socket        void Listen(object o)        {            Socket socketWatch = o as Socket;            while (true)            {                //等待用戶端的串連 並且建立一個負責通訊的Socket                socketSend = socketWatch.Accept();                ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "串連成功");                 //接受用戶端發送的資訊                Thread thread = new Thread(Receive);                thread.IsBackground = true;                thread.Start(socketSend);            }        }        void Receive(object o)        {            Socket socketSend = o as Socket;            while (true)            {                                byte[] buffer = new byte[1024 * 1024 * 2];                int r = socketSend.Receive(buffer);                if (r == 0)                {                    break;                }                string msg = Encoding.UTF8.GetString(buffer,0,r);                ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + msg);            }        }        void ShowMsg(string msg)        {            txtLog.AppendText(msg+"\r\n");        }                }}

//winform用戶端

//用戶端using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Net.Sockets;using System.Net;using System.Threading;namespace Client{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();            CheckForIllegalCrossThreadCalls = false;        }        Socket socketSend;        private void button1_Click(object sender, EventArgs e)        {            socketSend = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);            //擷取伺服器ip            IPAddress ip = IPAddress.Parse(txtIp.Text.Trim());            //擷取連接埠號碼            IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text.Trim()));            //串連伺服器            socketSend.Connect(point);            //開啟一個線程不斷接受伺服器端發送過來的資訊            Thread thread = new Thread(Receive);            thread.IsBackground = true;            thread.Start();        }        /// <summary>        /// 接受服務端發送的資訊        /// </summary>        void Receive()        {                        while (true)            {                byte[] buffer = new byte[1024 * 1024 * 2];                int r = socketSend.Receive(buffer);                if (r == 0)                {                    break;                }                string msg = Encoding.UTF8.GetString(buffer, 0, r);                ShowMsg(socketSend.RemoteEndPoint + ":" + msg);                            }        }        /// <summary>        /// 客服端向伺服器端發送資訊        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void button2_Click(object sender, EventArgs e)        {            string msg = this.txtMsg.Text.Trim();            byte[] buffer = Encoding.UTF8.GetBytes(msg);            socketSend.Send(buffer);        }        void ShowMsg(string msg)        {            txtLog.AppendText(msg + "\r\n");        }    }}

iOS socket 筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.