本文实例讲述了C#中Socket通信用法。分享给大家供大家参考。具体如下:

一、UDP方式:

服务器端代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

static void Main(string[] args)

{

  int recv;

  byte[] data = new byte[1024];

  IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//定义一网络端点

  Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket

  newsock.Bind(ipep);//Socket与本地的一个终结点相关联

  Console.WriteLine("Waiting for a client..");

  IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址

  EndPoint Remote = (EndPoint)(sender);//

  recv = newsock.ReceiveFrom(data, ref Remote);//接受数据     

  Console.WriteLine("Message received from{0}:", Remote.ToString());

  Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

  string welcome = "Welcome to my test server!";

  data = Encoding.ASCII.GetBytes(welcome);

  newsock.SendTo(data, data.Length, SocketFlags.None, Remote);

  while (true)

  {

    data = new byte[1024];

    recv = newsock.ReceiveFrom(data, ref Remote);

    Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

    newsock.SendTo(data, recv, SocketFlags.None, Remote);

  }

}

客户端代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

void MainInfo()

{

  byte[] data = new byte[1024];//定义一个数组用来做数据的缓冲区

  string input, stringData;

  IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.1.21"), 9050);

  Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

  string welcome = "Hello,are you there?";

  data = Encoding.ASCII.GetBytes(welcome);

  server.SendTo(data, data.Length, SocketFlags.None, ipep);//将数据发送到指定的终结点

  IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

  EndPoint Remote = (EndPoint)sender;

  data = new byte[1024];

  int recv = server.ReceiveFrom(data, ref Remote);//接受来自服务器的数据

  Console.WriteLine("Message received from{0}:", Remote.ToString());

  Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

  while (true)//读取数据

  {

    input = richTextBox1.Text;//从键盘读取数据

    if (input == "text")//结束标记

    {

      break;

    }

    server.SendTo(Encoding.ASCII.GetBytes(input), Remote);//将数据发送到指定的终结点Remote

    data = new byte[1024];

    recv = server.ReceiveFrom(data, ref Remote);//从Remote接受数据

    stringData = Encoding.ASCII.GetString(data, 0, recv);

    Console.WriteLine(stringData);

  }

  Console.WriteLine("Stopping client");

  server.Close();

}

二、TCP方式:

服务器端代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

Socket serverSocket = null;

Thread clientThread = null;

Socket clientSocket = null;

Thread thread = null;

IPAddress ips = null;

PEndPoint ipep = null;

void ServerStart()

{

  ips = Dns.GetHostAddresses(Dns.GetHostName())[0];

  //创建IPEndPoint实例 

  ipep = new IPEndPoint(ips, 9050);

  //创建一个套接字 

  serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

  serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

  //将所创建的套接字与IPEndPoint绑定 

  serverSocket.Bind(ipep);

  //设置套接字为收听模式 

  serverSocket.Listen(20);

  while (listenalive)

  {

    try

    {

      //在套接字上接收接入的连接 

      clientSocket = serverSocket.Accept();

      clientThread = new Thread(new ParameterizedThreadStart(ReceiveData));

      clientThread.Start(clientSocket);

    }

    catch (Exception ex)

    {

      WriteErrorLog(ex.Message);

      serverSocket.Close();

      serverSocket = null;

    }

  }

}

static void ReceiveData(object obj)

{

  bool keepalive = true;

  Socket s = obj as Socket;

  Byte[] buffer = new Byte[1024];

  //根据收听到的客户端套接字向客户端发送信息 

  IPEndPoint clientep = (IPEndPoint)s.RemoteEndPoint;

  Console.WriteLine("客户端ip:" + clientep.Address + " 端口:" + clientep.Port);

  string welcome = "连接服务器成功";

  buffer = System.Text.Encoding.Unicode.GetBytes(welcome);

  //向客户端发送“连接服务器成功”消息

  s.Send(buffer, buffer.Length, SocketFlags.None);

  buffer = new Byte[1024];

  int bufLen = 0;

  string content = string.Empty;

  while (true)

  {

    //在套接字上接收客户端发送的信息 

    bufLen = 0;

    try

    {

      bufLen = s.Receive(buffer);

      if (bufLen == 0)

      {

        break;

      }

      content += System.Text.Encoding.Unicode.GetString(buffer, 0, bufLen);

    }

    catch (Exception ex)

    {

      break; ;

    }

  }

  Send(s, content);

  s = null;

  buffer = null;

  clientep = null;

  Thread.CurrentThread.Abort();

}

客户端代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

void Send(string content)

{

  byte[] data = new byte[1024];

  newclient = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);

  ie = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ipadd), port);//服务器的IP和端口

  try

  {

    //因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。

    newclient.Connect(ie);

  }

  catch (System.Net.Sockets.SocketException e)

  {

    Console.WriteLine(e.ToString());

    return;

  }

  int recv = newclient.Receive(data);

  //连接服务器成功

  string stringdata = System.Text.Encoding.Unicode.GetString(data, 0, recv);

  if (stringdata == "连接服务器成功")

  {

    newclient.Send(System.Text.Encoding.Unicode.GetBytes(content));

    newclient.Shutdown(System.Net.Sockets.SocketShutdown.Send);

    data = new byte[1024];

    recv = newclient.Receive(data);

    string result = System.Text.Encoding.Unicode.GetString(data, 0, recv);    

    newclient.Shutdown(System.Net.Sockets.SocketShutdown.Receive);

    newclient.Close();

    MessageBox.Show(result);

  }

  else

  {

    MessageBox.Show("连接服务器失败", "友情提示");

  }

}

希望本文所述对大家的C#程序设计有所帮助。

C#中Socket通信用法实例详解相关推荐

  1. python编程字典100例_python中字典(Dictionary)用法实例详解

    本文实例讲述了python中字典(Dictionary)用法.分享给大家供大家参考.具体分析如下: 字典(Dictionary)是一种映射结构的数据类型,由无序的"键-值对"组成. ...

  2. python类初始化导入库_Python中optparser库用法实例详解

    本文研究的主要是Python中optparser库的相关内容,具体如下. 一直以来对optparser不是特别的理解,今天就狠下心,静下心研究了一下这个库.当然了,不敢说理解的很到位,但是足以应付正常 ...

  3. python print函数用法_Python3.2中Print函数用法实例详解

    本文实例讲述了Python3.2中Print函数用法.分享给大家供大家参考.具体分析如下: 1. 输出字符串 >>> strHello = 'Hello World' >> ...

  4. php定义枚举,PHP中Enum(枚举)用法实例详解

    本文实例讲述了PHP中Enum(枚举)用法.分享给大家供大家参考,具体如下: PHP其实有Enum类库的,需要安装perl扩展,所以不是php的标准扩展,因此代码的实现需要运行的php环境支持. (1 ...

  5. python 字典定义日志用法_python中字典(Dictionary)用法实例详解

    本文实例讲述了python中字典(Dictionary)用法.分享给大家供大家参考.具体分析如下: 字典(Dictionary)是一种映射结构的数据类型,由无序的"键-值对"组成. ...

  6. python argparse模块详解_python中argparse模块用法实例详解

    本文实例讲述了python中argparse模块用法.分享给大家供大家参考.具体分析如下: 平常在写命令行工具的时候,经常会带参数,所以用python中的argparse来实现. # -*- codi ...

  7. [转载] python里字典的用法_python中字典(Dictionary)用法实例详解

    参考链接: Python字典dictionary copy方法 本文实例讲述了python中字典(Dictionary)用法.分享给大家供大家参考.具体分析如下: 字典(Dictionary)是一种映 ...

  8. java中用法实例_java中Calendar类用法实例详解

    本文实例讲述了java中Calendar类用法.分享给大家供大家参考,具体如下: java中的Calendar在开发中经常被忽略,这篇博客总结一下这个类,对后面项目中使用时期的时候有帮助. Calen ...

  9. JavaScript中window.open用法实例详解

    本文较为详细的分析了JavaScript中window.open用法.分享给大家供大家参考.具体如下: 复制代码 代码如下: <script LANGUAGE="javascript& ...

最新文章

  1. #Ubuntu 18.04 安装tensorflow-gpu 1.9
  2. java常用的几种线程池
  3. java7新特性之Try-with-resources statement
  4. Runloop循环机制
  5. ubuntu16.04下面安装mongodb
  6. ES6 各浏览器支持情况
  7. python比较时间的最大值_时间戳的最大值
  8. Codeforces Round #256 (Div. 2)
  9. C语言 const 笔记
  10. ASN.1编解码:asn1c的版本分析-诺基亚
  11. python找思路_python 爬取贝壳的一些思路和方法设计(用地址找到小区名字)
  12. 数学建模算法与应用习题1-3 解析 MATLAB 整数规划
  13. Microsoft store下载速度过慢
  14. 怎么看cpu的好坏 图文告诉你电脑cpu怎么看
  15. 山东大学为什么火了_关于最近很“火”的话题,山东大学学伴制度的看法
  16. SQL语句常见面试题(一)
  17. 学习笔记-基于全局和局部对比自监督学习的高分辨率遥感图像语义分割-day1
  18. oracle数据库merge into,merge into 的用法
  19. 【Android每日一讲】2012.11.27 向左或向右 - RadioGroup组与onCheckedChanged事件
  20. C程序设计基础期末考试复习

热门文章

  1. java使用xml存储数据_聊一聊 Redis 数据内部存储使用到的数据结构
  2. eclipse没有dynamic web project_Microsoft Teams迎来Project与Roadmap功能集成
  3. vb mysql ado_VB中的ADO数据对象编程详解
  4. NRF24L01+ 自动重发,自动应答BUG
  5. 如何用python画一个心形图_求问怎样用python/python turtle画“心”
  6. springboot日志可视化_spring boot面试问题集锦
  7. 各种Arduino外设的用法,生动形象,相当好看!
  8. 半导体芯片原厂涨价及调价声明新增了这些!
  9. 电子元器件首饰!送给你喜欢的女孩!
  10. 建一个电赛交流群-大鱼机器人公众号专属