客户端:实现向服务器发送文件
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();
}
}
}