110,534
社区成员
发帖
与我相关
我的任务
分享
public partial class Form1 : Form
{
TcpClient tcp;
IPEndPoint remoteEP;
FileStream fs;
public Form1()
{
InitializeComponent();
tcp = new TcpClient();
tcp.Client.ReceiveTimeout = 2000;
remoteEP = new IPEndPoint(IPAddress.Parse("192.168.26.98"), 12345);
}
private void button1_Click(object sender, EventArgs e)
{
if (remoteEP != null)
{
tcp.Client.BeginConnect(remoteEP, callback, tcp.Client);
}
}
void callback(IAsyncResult ar)
{
Socket handler = (Socket)ar.AsyncState;
try
{
handler.EndConnect(ar);
}
catch (Exception ex)
{
MessageBoxShow(ex.Message);
}
try
{
byte[] bytes = Encoding.UTF8.GetBytes("Move.txt");
handler.Send(bytes);
}
catch (Exception ex)
{
MessageBoxShow(ex.Message);
}
try
{
byte[] receive = new byte[1024];
int count = 0;
fs = new FileStream("d:\\Move.txt", FileMode.OpenOrCreate);
//fs.Position = 0;
while (true)
{
count = handler.Receive(receive);
if (count > 0)
{
fs.Write(receive, 0, count);
}
else//注意,如果服务器端文件发送完毕后直接断开连接,则会进入这里。
{
fs.Flush();
fs.Close();
handler.Close();
MessageBoxShow("连接断开,可能是文件已经传输完毕。");
break;
}
}
}
catch (Exception ex)
{
if (fs != null)
{
fs.Flush();
fs.Close();
handler.Close();
}
MessageBox.Show(ex.Message);
}
}
void MessageBoxShow(string msg)
{
if (this.InvokeRequired)
{
Action showmsg = () => MessageBox.Show(msg);
this.Invoke(showmsg);
}
else
{
MessageBox.Show(msg);
}
}
}
if (File.Exists(file))
{
handler.SendFile(file);
handler.Close();
MessageBoxShow("发送完毕");
}
public partial class Form1 : Form
{
TcpListener tcplistener;
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 12345);
string basePath = "D:\\";
public static ManualResetEvent allDone = new ManualResetEvent(false);
public Form1()
{
InitializeComponent();
tcplistener = new TcpListener(localEndPoint);
tcplistener.Start(10);
}
private void button1_Click(object sender, EventArgs e)
{
Action l = () =>
{
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
tcplistener.BeginAcceptSocket(
new AsyncCallback(AcceptCallback1),
tcplistener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
};
l.BeginInvoke(null, null);
listView1.Items.Add("服务已开启");
button1.Enabled = false;
}
public void AcceptCallback1(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
TcpListener listener = (TcpListener)ar.AsyncState;
Socket handler = listener.EndAcceptSocket(ar);
byte[] receive = new byte[128];
try
{
int count = handler.Receive(receive);
string request = Encoding.UTF8.GetString(receive, 0, count);
string file = Path.Combine(basePath, request);
if (File.Exists(file))
{
handler.SendFile(file);
MessageBoxShow("发送完毕");
}
}
catch (Exception ex)
{
MessageBoxShow(ex.Message);
}
}
void MessageBoxShow(string msg)
{
if (this.InvokeRequired)
{
Action showmsg = () => MessageBox.Show(msg);
this.Invoke(showmsg);
}
else
{
MessageBox.Show(msg);
}
}
}