日期:2014-05-20  浏览次数:20924 次

求C#socket文件传输示例
最好有断点续传,异步传输,传输大文件的功能

------解决方案--------------------
断点续传也有一个配置文件和下载文件一起,它记录了上一次下载的位置
------解决方案--------------------
服务器端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace TCP
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}

IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2000);
Socket sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个
private void button1_Click(object sender, EventArgs e)
{
try
{
sk.Bind(ipe);//绑定(异常:在其上下文中,该请求的地址无效。)
MessageBox.Show("绑定服务器成功!", "提示");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"提示");
return;
}

//设置 监听队列 长度为10(同时能够处理 10个连接请求)
sk.Listen(10);

Thread myth = new Thread(new ThreadStart(get_client_msg));
myth.IsBackground = true;
myth.Start();
}

Socket sokMsg = null;
//等待客户发送信息.....
private void get_client_msg()
{
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
sokMsg = sk.Accept();
while (true)
{
//监听到请求,立即创建负责与该客户端套接字通信的套接字.注:当客户端绑定到本服务器时,才会读过此行堵塞状态。

bytes = sokMsg.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
MessageBox.Show(recvStr,"服务器端程序");
}
}

private void button2_Click(object sender, EventArgs e)
{
string sendStr = "这是来自服务器端的测试信息。\n";
byte[] bs = Encoding.UTF8.GetBytes(sendStr);
sokMsg.Send(bs);
}
}
------解决方案--------------------
客户端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace TCPClient
{
public partial class TCPClient : Form
{
public TCPClient()
{
InitializeComponent();
}

IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2000);//把ip和端口转化为IPEndPoint实例
Socket sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket

private void button1_Click(object sender, EventArgs e)
{
try
{
sk.Connect(ipe);//连接到服务器
MessageBox.Show("连接成功!", "提示");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"提示");
return;
}

Thread myth = new Thread(new ThreadStart(get_server_msg));
myth.IsBackground = true;
myth.Start();