TCP同步传送数据示例
本例子写了个简单的TCP数据传送功能。
没有使用BinaryWriter,BinaryReader,而是使用NetworkStream的Read和Write功能,同样这个也可以通过Socket的实现。
发送端程序:
[csharp]
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Net;
6. using System.Net.Sockets;
7. using System.IO;
8.
9. namespace Client
10. {
11. class Program
12. {
13. TcpClient tcpClient;
14. int port = 4444;
15. IPAddress serverIP;
16. NetworkStream ns;
17.
18. static void Main(string[] args)
19. {
20.
21. Program tcpConn = new Program();
22. tcpConn.Connect();
23. Console.ReadKey();
24. }
25.
26. private void Connect()
27. {
28. serverIP = IPAddress.Parse("10.108.13.27");
29. tcpClient = new TcpClient();
30. tcpClient.Connect(serverIP, port);
31. if (tcpClient!=null)
32. {
33. ns = tcpClient.GetStream();
34. //for (int i = 0; i < 10;i++ )
35. //{
36. // 发送数据
37. byte[] sendbyte = Encoding.Unicode.GetBytes("远看山有色");
38. ns.Write(sendbyte, 0, sendbyte.Length);
39. sendbyte = Encoding.Unicode.GetBytes("遥知不是雪");
40. ns.Write(sendbyte, 0, sendbyte.Length);
41. sendbyte = Encoding.Unicode.GetBytes("为有暗香来");
42. ns.Write(sendbyte, 0, sendbyte.Length);
43. //}
44.
45. }
46. }
47. }
48. }
这里将发送端程序的循环发送注释掉了,也就是只发送三行数据。
接收端的程序:
[csharp]
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Net;
6. using System.Net.Sockets;
7. using System.IO;
8. using System.Threading;
9.
10. namespace Server
11. {
12. class Program
13. {
14. TcpClient tcpClient;
15. TcpListener tcpListener;
16. IPAddress serverIP;
17. int port = 4444;
18. NetworkStream networkStream;
19.
20. static void Main(string[] args)
21. {
22. Program tcpConnect = new Program();
23. tcpConnect.listenTCPClient();
24. }
25.
26. private void listenTCPClient()
27. {
28. Console.WriteLine("开始监听:");
29. serverIP = IPAddress.Parse("10.108.13.27");
30. tcpListener = new TcpListener(serverIP, port);
31. tcpListener.Start();
32. try
33. {
34. while (true)
35. {
36. tcpClient = tcpListener.AcceptTcpClient();
37. if (tcpClient != null)
38. {
39. Console.WriteLine("接收到客户端连接!");
40. &nbs
补充:软件开发 , C# ,