c# socket网络编程接收发送数据示例代码

时间:2021-08-31 06:14:13 

代码分2块,server端:


class Program
    {
        static void Main(string[] args)
        {
            TcpListener lsner = new TcpListener(9000);
            lsner.Start();
            Console.WriteLine("started in port: 9000");
            while (true)
            {
                TcpClient client=lsner.AcceptTcpClient();
                Console.WriteLine("new client received. hashcode: {0}", client.GetHashCode());
                ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessTcpClient), client);
            }
            Console.ReadKey();
        }

        private static void ProcessTcpClient(object state)
        {
            TcpClient client=state as TcpClient;
            if(client==null)
                Console.WriteLine("client is null");

            NetworkStream ns=client.GetStream();
            StreamWriter sw = new StreamWriter(ns);
            sw.WriteLine("Welcome.");
            sw.Flush();
            sw.Close();
            client.Close();
        }

client端:


class Program
    {
        static void Main(string[] args)
        {
            IPAddress address = IPAddress.Parse("127.0.0.1");
            IPEndPoint ep=new IPEndPoint(address, 9000);
            TcpClient client = new TcpClient();
            client.Connect(ep);
            NetworkStream ns=client.GetStream();
            StreamReader sr = new StreamReader(ns);
            Console.WriteLine(sr.ReadToEnd());
            sr.Close();
            sr.Dispose();
            ns.Close();
            ns.Dispose();
            client.Close();
            Console.ReadKey();
        }
    }



c# socket网络编程接收发送数据示例代码
 

标签:c#,socket,网络编程,接收发送数据
0
投稿

猜你喜欢

  • Java单元测试工具之JUnit的使用

    2022-09-05 13:20:54
  • Java接口幂等性设计原理解析

    2022-12-22 12:27:01
  • Entity Framework主从表的增删改

    2023-10-05 18:56:27
  • C#识别出图片里的数字和字母

    2023-04-12 08:21:41
  • @RequestBody的使用案例代码

    2021-07-11 16:46:50
  • C#微信开发之接收 / 返回文本消息

    2021-08-21 14:37:11
  • 超全MyBatis动态代理详解(绝对干货)

    2023-11-14 02:28:19
  • C#实现3步手动建DataGridView的方法

    2021-10-13 22:35:56
  • C# Winfom 中ListBox的简单用法详解

    2023-03-14 20:38:47
  • 基于swing实现窗体拖拽和拉伸

    2023-11-12 22:32:40
  • 基于spring security实现登录注销功能过程解析

    2023-11-29 06:09:05
  • C#泛型详解及关键字作用

    2023-04-07 20:23:12
  • c# 解决IIS写Excel的权限问题

    2021-08-21 03:23:34
  • Mybatis基于注解形式的sql语句生成实例代码

    2023-03-07 03:48:11
  • mybatis in foreach 双层嵌套问题

    2023-11-24 12:55:47
  • myeclipse安装Spring Tool Suite(STS)插件的方法步骤

    2023-02-22 00:56:02
  • 详解Kotlin:forEach也能break和continue

    2022-05-03 01:24:10
  • Android TextWatcher监控EditText中的输入内容并限制其个数

    2022-08-18 13:27:41
  • 使用genymotion访问本地上Tomcat上数据的方法

    2022-11-23 05:51:43
  • 基于C#实现XML文件读取工具类

    2021-10-07 07:42:19
  • asp之家 软件编程 m.aspxhome.com