博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#网络示例
阅读量:6475 次
发布时间:2019-06-23

本文共 1994 字,大约阅读时间需要 6 分钟。

  hot3.png

using System;using System.IO;using System.Net;using System.Net.Sockets;using System.Text;class MyTcpListener{  public static void Main()  {     TcpListener server=null;       try    {      // Set the TcpListener on port 13000.      Int32 port = 13000;      IPAddress localAddr = IPAddress.Parse("127.0.0.1");      // TcpListener server = new TcpListener(port);      server = new TcpListener(localAddr, port);      // Start listening for client requests.      server.Start();      // Buffer for reading data      Byte[] bytes = new Byte[256];      String data = null;      // Enter the listening loop.      while(true)       {        Console.Write("Waiting for a connection... ");        // Perform a blocking call to accept requests.        // You could also user server.AcceptSocket() here.        TcpClient client = server.AcceptTcpClient();                    Console.WriteLine("Connected!");        data = null;        // Get a stream object for reading and writing        NetworkStream stream = client.GetStream();        int i;        // Loop to receive all the data sent by the client.        while((i = stream.Read(bytes, 0, bytes.Length))!=0)         {             // Translate data bytes to a ASCII string.          data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);          Console.WriteLine("Received: {0}", data);          // Process the data sent by the client.          data = data.ToUpper();          byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);          // Send back a response.          stream.Write(msg, 0, msg.Length);          Console.WriteLine("Sent: {0}", data);                    }        // Shutdown and end connection        client.Close();      }    }    catch(SocketException e)    {      Console.WriteLine("SocketException: {0}", e);    }    finally    {       // Stop listening for new clients.       server.Stop();    }    Console.WriteLine("\nHit enter to continue...");    Console.Read();  }   }

转载于:https://my.oschina.net/csmw00/blog/674017

你可能感兴趣的文章
Serial Communication Protocol Design Hints And Reference
查看>>
125.7. debug
查看>>
centos7安装nodejs
查看>>
docker常用命令
查看>>
centos locate搜索工具
查看>>
Fiori开发环境配置日志_单机版
查看>>
Creating Test Script With Bind Variable
查看>>
【RAC】 RAC For W2K8R2 安装--操作系统环境配置 (二)
查看>>
.run文件安装
查看>>
LVS负载均衡
查看>>
常见负面SEO方法,你应该知道的事?
查看>>
【Python】模块 fileinput
查看>>
如何开发自己的搜索帝国之ES图形化Kibana安装与使用
查看>>
麦克风采集与播放 (源码)
查看>>
最近的几个技术问题总结和答疑
查看>>
最小二乘法为什么使用误差平方和
查看>>
mysql (ICP) 索引条件下推对比ORACLE进行说明
查看>>
【中亦安图】关于数据库文件损坏风险的提醒(3)
查看>>
UDEV规则参数详细解释使用
查看>>
软件项目管理“固化、简化、标准化”
查看>>