iOS socket 笔记

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 *message=@"连接成功";

    

    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");
        }
    }
}

转载于:https://www.cnblogs.com/Dr-cyc-blogs/p/4169247.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值