本例子写了个简单的TCP数据传送功能。
没有使用BinaryWriter,BinaryReader,而是使用NetworkStream的Read和Write功能,同样这个也可以通过Socket的实现。
发送端程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Client
{
class Program
{
TcpClient tcpClient;
int port = 4444;
IPAddress serverIP;
NetworkStream ns;
static void Main(string[] args)
{
Program tcpConn = new Program();
tcpConn.Connect();
Console.ReadKey();
}
private void Connect()
{
serverIP = IPAddress.Parse("10.108.13.27");
tcpClient = new TcpClient();
tcpClient.Connect(serverIP, port);
if (tcpClient!=null)
{
ns = tcpClient.GetStream();
//for (int i = 0; i < 10;i++ )
//{
// 发送数据
byte[] sendbyte = Encoding.Unicode.GetBytes("远看山有色");
ns.Write(sendbyte, 0, sendbyte.Length);
sendbyte = Encoding.Unicode.GetBytes("遥知不是雪");
ns.Write(sendbyte, 0, sendbyte.Length);
sendbyte = Encoding.Unicode.GetBytes("为有暗香来");
ns.Write(sendbyte, 0, sendbyte.Length);
//}
}
}
}
}
这里将发送端程序的循环发送注释掉了,也就是只发送三行数据。
接收端的程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Server
{
class Program
{
TcpClient tcpClient;
TcpListener tcpListener;
IPAddress serverIP;
int port = 4444;
NetworkStream networkStream;
static void Main(string[] args)
{
Program tcpConnect = new Program();
tcpConnect.listenTCPClient();
}
private void listenTCPClient()
{
Console.WriteLine("开始监听:");
serverIP = IPAddress.Parse("10.108.13.27");
tcpListener = new TcpListener(serverIP, port);
tcpListener.Start();
try
{
while (true)
{
tcpClient = tcpListener.AcceptTcpClient();
if (tcpClient != null)
{
Console.WriteLine("接收到客户端连接!");
networkStream = tcpClient.GetStream();
Thread tcpClientThread = new Thread(new ParameterizedThreadStart(tcpReceive));
tcpClientThread.IsBackground = true;
tcpClientThread.Start(networkStream);
}
}
}
catch (System.Exception ex)
{
//
Console.WriteLine("监听出现错误");
}
}
private void tcpReceive(object obj)
{
NetworkStream ns = obj as NetworkStream;
// 循环接收客户端发送来的消息
while (true)
{
byte[] msg=new byte[128];
int count = ns.Read(msg, 0, 128);
string info = Encoding.Unicode.GetString(msg);
Console.WriteLine("接收到客户端发来:");
Console.WriteLine(info);
Console.WriteLine("\n");
}
}
}
}
这个时候的接收端的结果如图:
可以看出,虽然发送端连续发送了三次数据,但是接受端把这三次数据都当成一次接收了。因为发送端没有同步异步的差别,只要是发送,就直接放到数据缓冲区中,而接收端采用的是读指定的byte[]数组长度,所以只要在长度范围内都会读进来。而且这三条语句应该没有超过128个字节的数组长度。所有如果还有数据传送,应该还会读进来。
修改程序连续发送很多数据:
发送程序修改:
if (tcpClient!=null)
{
ns = tcpClient.GetStream();
for (int i = 0; i < 10;i++ )
{
// 发送数据
byte[] sendbyte = Encoding.Unicode.GetBytes("远看山有色");
ns.Write(sendbyte, 0, sendbyte.Length);
sendbyte = Encoding.Unicode.GetBytes("遥知不是雪");
ns.Write(sendbyte, 0, sendbyte.Length);
sendbyte = Encoding.Unicode.GetBytes("为有暗香来");
ns.Write(sendbyte, 0, sendbyte.Length);
}
}
添加了循环发送语句,这样总共发送的数据肯定会超过128字节。
接收端的接收情况如图:
可以看到,接收到每次要读满128字节的缓冲区才进行显示。
这里的情况和http://blog.csdn.net/weixingstudio/article/details/7635857这里提到的接收端等待发送端数据不一样,因为在那篇中用的BinaryWriter,BinaryReader来操作网络数据流,每次写入一个字符串,都会在写入的字符串的前面添加字符串的长度。这样每次读一个字符串的时候就会根据前面的长度来读取缓冲区的数据,如果缓冲区数据不够的话则进行阻塞等待数据,这里没有那么使用,所以不会进行阻塞,只要缓冲区有数据就可以读,当然,如果缓冲区没有数据还是会阻塞的。
修改程序,说明当缓冲区没有数据的时候接受会阻塞。
只需要注释掉发送方的发送语句:
for (int i = 0; i < 10;i++ )
{
发送数据
//byte[] sendbyte = Encoding.Unicode.GetBytes("远看山有色");
//ns.Write(sendbyte, 0, sendbyte.Length);
//sendbyte = Encoding.Unicode.GetBytes("遥知不是雪");
//ns.Write(sendbyte, 0, sendbyte.Length);
//sendbyte = Encoding.Unicode.GetBytes("为有暗香来");
//ns.Write(sendbyte, 0, sendbyte.Length);
}
这样,当运行服务器和客户端的时候,会有这样的结果:
可以看到,客户端没有发送数据过来,服务器端等待数据阻塞了,因为如果没有阻塞,会不停的输出空行,因为接收循环中存在这样一条 语句。
下面修改程序,让发送方进行发送延迟,看看接收方的反应。
修改的客户端程序如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Client
{
class Program
{
static void Main(string[] args)
{
Connect();
Console.ReadKey();
}
static void Connect()
{
TcpClient tcpClient;
int port = 4444;
IPAddress serverIP;
NetworkStream ns;
serverIP = IPAddress.Parse("10.108.13.27");
tcpClient = new TcpClient();
tcpClient.Connect(serverIP, port);
if (tcpClient!=null)
{
ns = tcpClient.GetStream();
for (int i = 0; i < 3;i++ )
{
// 发送数据
byte[] sendbyte = Encoding.Unicode.GetBytes("远看山有色");
ns.Write(sendbyte, 0, sendbyte.Length);
sendbyte = Encoding.Unicode.GetBytes("遥知不是雪");
ns.Write(sendbyte, 0, sendbyte.Length);
sendbyte = Encoding.Unicode.GetBytes("为有暗香来");
ns.Write(sendbyte, 0, sendbyte.Length);
Thread.Sleep(2000);
}
}
}
}
}
进行了三次发送,每次发送之后睡眠2秒。
看一下接收端的情况:
只有第一次的接收结果是正确的,其他的都是错误的。这是为什么呢?我也不明白具体为什么,还希望有能能给出明确解答。不过我个人认为,可能是在发送方休眠后再次发送数据的时候造成了混乱,解决这个问题的办法就是在发送之前添加一个发送长度的说明,接收方可以根据接收到的长度进行读取缓冲区。
然后修改程序,给接收方添加延时进行测试:
private void tcpReceive(object obj)
{
NetworkStream ns = obj as NetworkStream;
// 循环接收客户端发送来的消息
while (true)
{
byte[] msg=new byte[128];
int count = ns.Read(msg, 0, 128);
string info = Encoding.Unicode.GetString(msg);
Console.WriteLine("接收到客户端发来:");
Console.WriteLine(info);
Console.WriteLine("\n");
Thread.Sleep(2000);
}
}
这里出现了有意思的事情,让客户端延迟500ms,服务器延迟2000毫秒,这样服务器可以充分的等待客户端数据,可以看到第一次接受到了客户端的第一次发送的数据,而第二次接收到了客户端第二次和第三次发送的数据,因为这两次的数据加起来没有超过缓冲区大小。
再次修改程序,调整延迟时间,将客户端延迟设为1000ms,服务器延迟设为500ms,这样可能客户端的数据还没有发送来,服务器就读取了数据。
结果如图:
可见,在第二次发送还没有完全发送过来,服务器就读取了一次缓冲区。
由上面的分析可见,在进行TCP同步传送数据的开发过程中,让服务器和客户端进行搭配的传送数据的过程非常重要。然而, 自己手动控制传送数据大小还有延迟在调试过程中非常麻烦,而且可能效果很差,会发生不可控制的效果。最好的方法就是用BinaryWriter,BinaryReader控制数据的发送和接收,以前我没有用过这种方式,但是使用以后发现太方便了。因为BinaryWriter在发送一个字符串之前,会计算字符串的长度,将长度添加到字符串的前面,BinaryReader在接收的时候会根据提起的前导字符串长度进行读取缓冲区,如果长度不够,则进入数据接收阻塞,知道等到有足够的数据长度可以读取。
下面修改程序,利用BinaryWriter,BinaryReader操作数据的传送。
客户端程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Client
{
class Program
{
static void Main(string[] args)
{
Connect();
Console.ReadKey();
}
static void Connect()
{
TcpClient tcpClient;
int port = 4444;
IPAddress serverIP;
NetworkStream ns;
BinaryWriter bw;
serverIP = IPAddress.Parse("10.108.13.27");
tcpClient = new TcpClient();
tcpClient.Connect(serverIP, port);
if (tcpClient!=null)
{
ns = tcpClient.GetStream();
bw = new BinaryWriter(ns);
//for (int i = 0; i < 3;i++ )
//{
bw.Write("轻轻地我走了,正如我轻轻地来!");
bw.Flush();
bw.Write("我挥一挥衣袖,不带走一片云彩!");
bw.Flush();
bw.Write("那河畔的金柳,是夕阳中的新娘,波光里的艳影,在我的心头荡漾。");
bw.Flush();
//Thread.Sleep(1000);
//}
}
}
}
}
服务器端程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Server
{
class Program
{
TcpClient tcpClient;
TcpListener tcpListener;
IPAddress serverIP;
int port = 4444;
NetworkStream networkStream;
BinaryReader br;
static void Main(string[] args)
{
Program tcpConnect = new Program();
tcpConnect.listenTCPClient();
}
private void listenTCPClient()
{
Console.WriteLine("开始监听:");
serverIP = IPAddress.Parse("10.108.13.27");
tcpListener = new TcpListener(serverIP, port);
tcpListener.Start();
try
{
while (true)
{
tcpClient = tcpListener.AcceptTcpClient();
if (tcpClient != null)
{
Console.WriteLine("接收到客户端连接!");
networkStream = tcpClient.GetStream();
Thread tcpClientThread = new Thread(new ParameterizedThreadStart(tcpReceive));
tcpClientThread.IsBackground = true;
tcpClientThread.Start(networkStream);
}
}
}
catch (System.Exception ex)
{
//
Console.WriteLine("监听出现错误");
}
}
private void tcpReceive(object obj)
{
NetworkStream ns = obj as NetworkStream;
br = new BinaryReader(ns);
// 循环接收客户端发送来的消息
while (true)
{
string msg = br.ReadString();
Console.WriteLine(msg);
}
}
}
}
服务器端运行结果:
可以看到,通过BinaryWriter, BinaryReader发送数据和接收数据,都是获得正确的结果。
然后修改程序,增加循环发送,并增加发送延迟进行测试。
客户端延迟调整:
for (int i = 0; i < 3;i++ )
{
bw.Write("轻轻地我走了,正如我轻轻地来!");
bw.Flush();
bw.Write("我挥一挥衣袖,不带走一片云彩!");
bw.Flush();
bw.Write("那河畔的金柳,是夕阳中的新娘,波光里的艳影,在我的心头荡漾。");
bw.Flush();
Thread.Sleep(1000);
}
接收端接收结果:
同样的,给服务器添加延迟:
private void tcpReceive(object obj)
{
NetworkStream ns = obj as NetworkStream;
br = new BinaryReader(ns);
// 循环接收客户端发送来的消息
while (true)
{
string msg = br.ReadString();
Console.WriteLine(msg);
Thread.Sleep(500);
}
}
运行结果:
同样是正确的输出,然后再次调整延迟,让客户端延迟2000ms,服务器延迟500ms,运行结果:
还是正确的。
可以看到,BinaryWriter和BinaryReader可以在很大程度上帮助我们进行网络通信的编程操作。