同事在他负责的项目中想使用Socket传送文件,我就写了一个测试的程序.
为了简单起见,测试里没有用多线程和异步方式.只是能把文件传过去.呵呵.代码如下:
服务器端:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net.Sockets;
using System.Net;
namespace TransmitFileServer {
public class Form1 : System.Windows.Forms.Form {
private const string CMDGETFILE="GetTestFile";
private System.Net.Sockets.TcpListener listener=null;
private System.Windows.Forms.Button btnListen;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtStatus;
private System.ComponentModel.Container components = null;
public Form1() {
InitializeComponent();
string hostname=Dns.GetHostName(); //获得主机名
IPHostEntry entry=Dns.Resolve(hostname); //通过主机名得到IP列表
IPEndPoint point=new IPEndPoint(entry.AddressList[0],10000); //用第0个IP和10000端口实例化IPEndPoint
listener=new TcpListener(point); //也可以用其它的构造函数
}
protected override void Dispose( bool disposing ) {
if( disposing ) {
if (components != null) {
components.Dispose();
}
}
base.Dispose( disposing );
}
Windows 窗体设计器生成的代码
[STAThread]
static void Main() {
Application.Run(new Form1());
}
private void btnListen_Click(object sender, System.EventArgs e) {
try {
this.txtStatus.Text=string.Format("服务器正监听的IP为:{0},端口为:{1}",
((IPEndPoint)listener.LocalEndpoint).Address,((IPEndPoint)listener.LocalEndpoint).Port);
this.listener.Start();
System.Net.Sockets.TcpClient client = this.listener.AcceptTcpClient();
System.Net.Sockets.NetworkStream stream = client.GetStream();
while(true) {
while(stream.DataAvailable) {
byte[] buff=new byte[1024];
int len=stream.Read(buff,0,buff.Length);
string cmd=System.Text.Encoding.Unicode.GetString(buff,0,len);
if (cmd==CMDGETFILE) {
System.IO.FileStream fs=System.IO.File.Open("Test.dat",System.IO.FileMode.Open,
System.IO.FileAccess.Read);
System.IO.BinaryReader br=new System.IO.BinaryReader(fs);
try {
this.txtStatus.Text="正在传输文件...";
while ((len=br.Read(buff,0,buff.Length))!=0) {
if(stream.CanWrite) {
stream.Write(buff,0,len);
}
}
stream.Flush();
stream.Close();
this.txtStatus.Text="传输文件完毕!";
return;
}
catch(Exception ex) {
this.txtStatus.Text="错误:"+ex.Message;
return;
}
finally {
br.Close();
}
}
else {
this.txtStatus.Text="命令字非法!";
}
}
}
}
catch(Exception ex) {
MessageBox.Show(ex.Message);
}
}
}
}
客户端:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Net.Sockets;
using System.Net;
namespace GetFileClient {
public class Form1 : System.Windows.Forms.Form {
private System.Net.Sockets.TcpClient client=null;
private const string CMDGETFILE="GetTestFile";
private System.Windows.Forms.TextBox txtStatus;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnConnect;
private System.Windows.Forms.Button btnReceive;
private System.ComponentModel.Container components = null;
public Form1() {
InitializeComponent();
}
protected override void Dispose( bool disposing ) {
if( disposing ) {
if (components != null) {
components.Dispose();
}
}
base.Dispose( disposing );
}
Windows 窗体设计器生成的代码
[STAThread]
static void Main() {
Application.Run(new Form1());
}
private void btnConnect_Click(object sender, System.EventArgs e) {
IPAddress ip=IPAddress.Parse("10.0.0.153");
IPEndPoint remotepoint=new IPEndPoint(ip,10000);
client=new TcpClient();
try {
client.Connect(remotepoint);
this.txtStatus.Text="连接成功!";
}
catch(Exception ex) {
this.txtStatus.Text="错误:"+ex.Message;
client=null;
}
}
private void btnReceive_Click(object sender, System.EventArgs e) {
if(client==null) {
MessageBox.Show("先连接服务器!");
return;
}
NetworkStream stream=client.GetStream();
string cmd=CMDGETFILE;
byte[] bytcmd=System.Text.Encoding.Unicode.GetBytes(cmd);
try {
if (stream.CanWrite) {
this.txtStatus.Text="发送命令!";
stream.Write(bytcmd,0,bytcmd.Length);
while(true) {
if(stream.DataAvailable) {
if(stream.CanRead) {
FileStream fs=File.Open("Test.dat",FileMode.OpenOrCreate,FileAccess.Write);
BinaryWriter bw=new BinaryWriter(fs);
try {
this.txtStatus.Text="正在接收文件";
byte[] buff=new byte[1024];
int len=0;
while((len=stream.Read(buff,0,buff.Length))!=0) {
bw.Write(buff,0,len);
bw.Flush();
}
this.txtStatus.Text="接收完毕!";
return;
}
catch(Exception ex) {
this.txtStatus.Text="错误:"+ex.Message;
return;
}
finally {
bw.Close();
}
}
}
}
}
}
catch(Exception ex) {
MessageBox.Show(ex.Message);
}
}
}
}
由于小弟对这个也是一知半解,所以也就不做注解说明了,以免贻笑大方贻笑大方,呵呵.
为了简单起见,测试里没有用多线程和异步方式.只是能把文件传过去.呵呵.代码如下:
服务器端:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net.Sockets;
using System.Net;
namespace TransmitFileServer {
public class Form1 : System.Windows.Forms.Form {
private const string CMDGETFILE="GetTestFile";
private System.Net.Sockets.TcpListener listener=null;
private System.Windows.Forms.Button btnListen;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtStatus;
private System.ComponentModel.Container components = null;
public Form1() {
InitializeComponent();
string hostname=Dns.GetHostName(); //获得主机名
IPHostEntry entry=Dns.Resolve(hostname); //通过主机名得到IP列表
IPEndPoint point=new IPEndPoint(entry.AddressList[0],10000); //用第0个IP和10000端口实例化IPEndPoint
listener=new TcpListener(point); //也可以用其它的构造函数
}
protected override void Dispose( bool disposing ) {
if( disposing ) {
if (components != null) {
components.Dispose();
}
}
base.Dispose( disposing );
}
Windows 窗体设计器生成的代码
[STAThread]
static void Main() {
Application.Run(new Form1());
}
private void btnListen_Click(object sender, System.EventArgs e) {
try {
this.txtStatus.Text=string.Format("服务器正监听的IP为:{0},端口为:{1}",
((IPEndPoint)listener.LocalEndpoint).Address,((IPEndPoint)listener.LocalEndpoint).Port);
this.listener.Start();
System.Net.Sockets.TcpClient client = this.listener.AcceptTcpClient();
System.Net.Sockets.NetworkStream stream = client.GetStream();
while(true) {
while(stream.DataAvailable) {
byte[] buff=new byte[1024];
int len=stream.Read(buff,0,buff.Length);
string cmd=System.Text.Encoding.Unicode.GetString(buff,0,len);
if (cmd==CMDGETFILE) {
System.IO.FileStream fs=System.IO.File.Open("Test.dat",System.IO.FileMode.Open,
System.IO.FileAccess.Read);
System.IO.BinaryReader br=new System.IO.BinaryReader(fs);
try {
this.txtStatus.Text="正在传输文件...";
while ((len=br.Read(buff,0,buff.Length))!=0) {
if(stream.CanWrite) {
stream.Write(buff,0,len);
}
}
stream.Flush();
stream.Close();
this.txtStatus.Text="传输文件完毕!";
return;
}
catch(Exception ex) {
this.txtStatus.Text="错误:"+ex.Message;
return;
}
finally {
br.Close();
}
}
else {
this.txtStatus.Text="命令字非法!";
}
}
}
}
catch(Exception ex) {
MessageBox.Show(ex.Message);
}
}
}
}
客户端:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Net.Sockets;
using System.Net;
namespace GetFileClient {
public class Form1 : System.Windows.Forms.Form {
private System.Net.Sockets.TcpClient client=null;
private const string CMDGETFILE="GetTestFile";
private System.Windows.Forms.TextBox txtStatus;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnConnect;
private System.Windows.Forms.Button btnReceive;
private System.ComponentModel.Container components = null;
public Form1() {
InitializeComponent();
}
protected override void Dispose( bool disposing ) {
if( disposing ) {
if (components != null) {
components.Dispose();
}
}
base.Dispose( disposing );
}
Windows 窗体设计器生成的代码
[STAThread]
static void Main() {
Application.Run(new Form1());
}
private void btnConnect_Click(object sender, System.EventArgs e) {
IPAddress ip=IPAddress.Parse("10.0.0.153");
IPEndPoint remotepoint=new IPEndPoint(ip,10000);
client=new TcpClient();
try {
client.Connect(remotepoint);
this.txtStatus.Text="连接成功!";
}
catch(Exception ex) {
this.txtStatus.Text="错误:"+ex.Message;
client=null;
}
}
private void btnReceive_Click(object sender, System.EventArgs e) {
if(client==null) {
MessageBox.Show("先连接服务器!");
return;
}
NetworkStream stream=client.GetStream();
string cmd=CMDGETFILE;
byte[] bytcmd=System.Text.Encoding.Unicode.GetBytes(cmd);
try {
if (stream.CanWrite) {
this.txtStatus.Text="发送命令!";
stream.Write(bytcmd,0,bytcmd.Length);
while(true) {
if(stream.DataAvailable) {
if(stream.CanRead) {
FileStream fs=File.Open("Test.dat",FileMode.OpenOrCreate,FileAccess.Write);
BinaryWriter bw=new BinaryWriter(fs);
try {
this.txtStatus.Text="正在接收文件";
byte[] buff=new byte[1024];
int len=0;
while((len=stream.Read(buff,0,buff.Length))!=0) {
bw.Write(buff,0,len);
bw.Flush();
}
this.txtStatus.Text="接收完毕!";
return;
}
catch(Exception ex) {
this.txtStatus.Text="错误:"+ex.Message;
return;
}
finally {
bw.Close();
}
}
}
}
}
}
catch(Exception ex) {
MessageBox.Show(ex.Message);
}
}
}
}
由于小弟对这个也是一知半解,所以也就不做注解说明了,以免贻笑大方贻笑大方,呵呵.