C# Server Socket

该博客展示了如何使用C#创建一个TCP服务器Socket,监听127.0.0.1的3333端口,实现数据的发送和接收。服务器接收到连接请求后,启动后台线程进行数据的发送和接收。发送线程不断发送JSON格式的消息,而接收线程接收客户端数据并作出响应。
摘要由CSDN通过智能技术生成
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using LitJson;

public class Program{
    static Socket serverSocket;
    static Socket listenScoket;
    static int byt;
    static byte[] buf;
    static byte[] bufsend;
    static string str;
    static Thread threadSend, threadRec;

    public static void Main (string[] args){
        serverSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint ipEndpoint = new IPEndPoint (IPAddress.Parse ("127.0.0.1"), 3333);
        serverSocket.Bind (ipEndpoint);
        serverSocket.Listen (20);
        buf = new byte[1024];
        bufsend = new byte[1024];

        listenScoket = serverSocket.Accept ();

        if (listenScoket.Connected) {
//            threadRec = new Thread (new ThreadStart(ReceiveSocket));
//            threadRec.IsBackground = true;
//            threadRec.Start ();

            threadSend = new Thread (new ThreadStart (SendSocket));
            threadSend.IsBackground = true;
            threadSend.Start ();

        } else {
            Console.WriteLine ("fail");
        }
                
        Console.ReadKey ();
    }

    public static void SendSocket(){
        while (true) {
//            string userid = Console.ReadLine ();
//            string state = Console.ReadLine ();
//            string sends = "{\"userid\":\"" + userid + "\",\"state\":\"" + state + "\"}";
            string sends = "{\"server\":\"00\"}";
            bufsend = Encoding.UTF8.GetBytes (sends);
            listenScoket.Send (bufsend);
        }
    }
        
    public static void ReceiveSocket(){
        while(true){
            byt = listenScoket.Receive(buf);
            if(byt>0){
                str = Encoding.UTF8.GetString(buf);
                Console.WriteLine(str);

                bufsend = Encoding.UTF8.GetBytes ("{\"userid\":\"id123\",\"state\":\"03\"}");
                listenScoket.Send (bufsend);
            }
        }
    }
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值