点击此处下载源代码
客户端:实现向服务器发送文件
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net.Sockets;
using System.Net;
namespace tcpclient
{
class tcpclient
{
private static int portNum = 11000;
static void Main(string[] args)
{
//第一步:读取文件
Console.WriteLine("本程序实现向服务器发送文件...");
FileStream fs = File.Open("http://www.cnblogs.com/img.gif", FileMode.Open);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
fs.Close();
//第二步:发送文件
try
{
TcpClient client = new TcpClient(System.Net.Dns.GetHostName(), portNum);
NetworkStream ns = client.GetStream();
ns.Write(buffer, 0, buffer.Length);
ns.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
服务器端:不断接收客户端的输入
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net.Sockets;
using System.Net;
namespace tcpfile
{
class tcpserver
{
private const int portNum = 11000;
static void Main(string[] args)
{
bool done = false;
//TcpListener listener = new TcpListener(portNum); //根据VS2005 MSDN 此方法已经过时,不再使用
// IPEndPoint类将网络标识为IP地址和端口号
TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, portNum));
listener.Start();
while (!done)
{
Console.Write("Waiting for connection...");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Connection accepted.");
NetworkStream ns = client.GetStream();
byte[] tempBuffer = new byte[4096];
FileStream fs = File.Open(new Random().Next().ToString() + ".gif", FileMode.CreateNew);
int bytesRead = 0;
do
{
bytesRead = ns.Read(tempBuffer, 0, 4096);
fs.Write(tempBuffer, 0, bytesRead);
}while (bytesRead > 0);
fs.Close();
client.Close();
Console.WriteLine("file accepted.");
}
listener.Stop();
}
}
}
/* 如果不是文件的话,可以在内存中存储一个临时内存流,以便后续处理,如:赋给Image控件,压缩流等。
* 一种典型的从客户端读取流的方法
NetworkStream clientStreams = client.GetStream();
int bufferSize = 4096;
byte[] responseBuffer = new byte[bufferSize];
MemoryStream memStream = new MemoryStream();
int bytesRead = 0;
do
{
bytesRead = clientStream.Read(responseBuffer, 0, bufferSize);
memStream.Write(responseBuffer, 0, bytesRead);
} while (bytesRead > 0);
*/
/*
* 这种模式,是不被 NetworkStream clientStreams = client.GetStream(); 所支持的
byte[] buffer = new byte[clientStreams.Length];
clientStream.Read(buffer, 0, (int)fs.Length);
*/