首页 > 编程语言 >C# Socket Demo

C# Socket Demo

时间:2023-01-05 17:59:24浏览次数:40  
标签:Socket C# Demo void System server client using

通过函数回调机制实现的异步,回调函数中的逻辑保证在IO-Bound操作后执行,而线程不会在IO—Bound操作时阻塞等待
ps:IO—Bound表示需要一段时间等待的io逻辑

Client

using System.Text;
using System;
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SocketClient : MonoBehaviour {

    private Socket server;
    private byte[] buf = new byte[1024];
    
    void Start() {
        server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        server.Connect("192.168.1.4", 8054);

        // 异步接收数据
        StartReceive();

        // 向server发送消息
        Send();
    }

    void StartReceive() {
        server.BeginReceive(buf, 0, buf.Length, SocketFlags.None, ReceiveCallback, null);
    }

    void ReceiveCallback(IAsyncResult res) {
        int len = server.EndReceive(res);
        if(len == 0) return;
        string s = Encoding.UTF8.GetString(buf, 0, len);
        Debug.Log(s);

        StartReceive();
    }

    void Send() {
        server.Send(Encoding.UTF8.GetBytes("一条来自client的消息!"));
    }

    // Update is called once per frame
    void Update() {
        
    }
}

Server

using System.Text;
using System.Net;
using System.Net.Sockets;
class Program {
    private static Socket server;
    private static byte[] buf = new byte[1024];
    static void Main(string[] args) {
        server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        server.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.4"), 8054));

        server.Listen(0);

        StartAccept();

        // 阻塞
        Console.Read();
    }

    static void StartReceive(Socket client) {
        client.BeginReceive(buf, 0, buf.Length, SocketFlags.None, ReceiveCallback, client);
    }

    static void ReceiveCallback(IAsyncResult res) {
        Socket client = res.AsyncState as Socket;

        Send(client);
        
        int len = client.EndReceive(res);
        if(len == 0) return;
        string s = Encoding.UTF8.GetString(buf, 0, len);
        System.Console.WriteLine(s);

        StartReceive(client);
    }

    static void StartAccept() {
        server.BeginAccept(AcceptCallback, null);
    }

    static void AcceptCallback(IAsyncResult res) {
        Socket client = server.EndAccept(res);
        StartReceive(client);

        StartAccept();
    }

    static void Send(Socket client) {
        client.Send(Encoding.UTF8.GetBytes("一条来自Server的消息!"));
    }
}

标签:Socket,C#,Demo,void,System,server,client,using
From: https://www.cnblogs.com/flow-coding/p/17028425.html

相关文章