C# tcp socket客户端从服务器下载文件
目前我有这个问题。客户端仅第一次从服务器成功下载。第二次它不起作用(什么也没有发生,没有崩溃)。这是双方的代码:
在客户端,在 mainForm 中,如果我单击下载按钮,我将从另一个类 loginForm 调用方法 sendComment(string request)。
在服务器端,收到客户端的字符串请求后,服务器将调用sendComment(string listFiles)。 listFiles 包含客户端需要下载的所有文件的名称和大小。
字符串listFiles格式:“commitRequest mName usID fiName1 fiSize1 fiName2 fiSize2...”。客户端收到此字符串后,将请求字符串中的每个文件。
客户端:
登录表单:
private void Connect()
{
try
{
serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serversocket.Blocking = true;
IPHostEntry IPHost = Dns.Resolve(textBox1.Text);
string[] aliases = IPHost.Aliases;
IPAddress[] addr = IPHost.AddressList;
IPEndPoint ipepServer = new IPEndPoint(addr[0], 8090);
serversocket.Connect(ipepServer);
clientsock = serversocket;
Thread MainThread = new Thread(new ThreadStart(listenclient));
MainThread.Start();
MessageBox.Show("Connected successfully", "Infomation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
catch (Exception eee)
{
MessageBox.Show("Socket Connect Error.\n\n" + eee.Message + "\nPossible Cause: Server Already running. Check the tasklist for running processes", "Startup Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
}
void listenclient()
{
Socket sock = clientsock;
string cmd = server;
byte[] sender = System.Text.Encoding.ASCII.GetBytes("CLIENT " + cmd);
sock.Send(sender, sender.Length, 0);
while (sock != null)
{
cmd = "";
byte[] recs = new byte[32767];
int rcount = sock.Receive(recs, recs.Length, 0);
string clientmessage = System.Text.Encoding.ASCII.GetString(recs);
clientmessage = clientmessage.Substring(0, rcount);
string smk = clientmessage;
cmdList = null;
cmdList = clientmessage.Split(' ');
string execmd = cmdList[0];
sender = null;
sender = new Byte[32767];
string parm1 = "";
if (execmd == "CommitRequest")
{
for (int i = 3; i < cmdList.Length - 1; i++)
{
if (i % 2 == 1)
{
sendComment("downloadFile " + cmdList[i]); // after receiving this, server will upload the file requested
downloadMFromServer(sock, cmdList[2], cmdList[1], cmdList[i], cmdList[i + 1]);
}
}
continue;
}
}
private void downloadMFromServer(Socket s, string userID, string mName, string fileN, string fileS)
{
Socket sock = s;
string rootDir;
rootDir = @"C:\Client Data" + "\\" + userID + "\\" + mName;
Directory.CreateDirectory(rootDir);
System.IO.FileStream fout = new System.IO.FileStream(rootDir + "\\" + fileN, FileMode.Create, FileAccess.Write);
NetworkStream nfs = new NetworkStream(sock);
long size = int.Parse(fileS);
long rby = 0;
try
{
while (rby < size)
{
byte[] buffer = new byte[1024];
int i = nfs.Read(buffer, 0, buffer.Length);
fout.Write(buffer, 0, (int)i);
rby = rby + i;
}
fout.Close();
}
catch (Exception ed)
{
Console.WriteLine("A Exception occured in file transfer" + ed.ToString());
MessageBox.Show(ed.Message);
}
}
点击第一次下载按钮后,文件成功下载到客户端,然后我删除了所有下载的文件,然后我第二次点击下载按钮,但这一次不起作用。
文件未下载。我尝试调试,它没有显示任何错误,但客户端应用程序在从服务器接收字符串 listFiles 的步骤处停止。我的意思是客户端发送的字符串正确。服务器收到字符串重新正常。服务器发送字符串 listFiles 正常。但客户端没有得到listFiles。有谁知道为什么它不起作用?提前感谢您的帮助。
这是 sendComment 方法的代码,对于客户端和服务器应用程序来说都是相同的。
public void sendComment(string comment)
{
Socket serversock = serversocket;
if (serversock == null)
{
MessageBox.Show("Client not connected", "Connect Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
byte[] b = System.Text.Encoding.ASCII.GetBytes(comment + " ");
serversock.Send(b, b.Length, 0);
}
我不上传服务器端代码,因为我认为它没有任何问题,而且这篇文章会有点长,但如果您需要的话,我会发布它。
Currently I have this problem. Client downloads from server successfully only the 1st time. The 2nd time it doesn't work(nothing happens, no crash). Here the code from both side:
At client, in mainForm, If I click the download button, I will call a method sendComment(string request) from another class, loginForm.
At server, after receiving string request from client, server will call sendComment(string listFiles). listFiles consists of all files' names and sizes that client need to download.
The string listFiles format: "commitRequest mName usID fiName1 fiSize1 fiName2 fiSize2...".After receive this string, client will request each file in string.
Client side:
loginForm:
private void Connect()
{
try
{
serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serversocket.Blocking = true;
IPHostEntry IPHost = Dns.Resolve(textBox1.Text);
string[] aliases = IPHost.Aliases;
IPAddress[] addr = IPHost.AddressList;
IPEndPoint ipepServer = new IPEndPoint(addr[0], 8090);
serversocket.Connect(ipepServer);
clientsock = serversocket;
Thread MainThread = new Thread(new ThreadStart(listenclient));
MainThread.Start();
MessageBox.Show("Connected successfully", "Infomation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
catch (Exception eee)
{
MessageBox.Show("Socket Connect Error.\n\n" + eee.Message + "\nPossible Cause: Server Already running. Check the tasklist for running processes", "Startup Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
}
void listenclient()
{
Socket sock = clientsock;
string cmd = server;
byte[] sender = System.Text.Encoding.ASCII.GetBytes("CLIENT " + cmd);
sock.Send(sender, sender.Length, 0);
while (sock != null)
{
cmd = "";
byte[] recs = new byte[32767];
int rcount = sock.Receive(recs, recs.Length, 0);
string clientmessage = System.Text.Encoding.ASCII.GetString(recs);
clientmessage = clientmessage.Substring(0, rcount);
string smk = clientmessage;
cmdList = null;
cmdList = clientmessage.Split(' ');
string execmd = cmdList[0];
sender = null;
sender = new Byte[32767];
string parm1 = "";
if (execmd == "CommitRequest")
{
for (int i = 3; i < cmdList.Length - 1; i++)
{
if (i % 2 == 1)
{
sendComment("downloadFile " + cmdList[i]); // after receiving this, server will upload the file requested
downloadMFromServer(sock, cmdList[2], cmdList[1], cmdList[i], cmdList[i + 1]);
}
}
continue;
}
}
private void downloadMFromServer(Socket s, string userID, string mName, string fileN, string fileS)
{
Socket sock = s;
string rootDir;
rootDir = @"C:\Client Data" + "\\" + userID + "\\" + mName;
Directory.CreateDirectory(rootDir);
System.IO.FileStream fout = new System.IO.FileStream(rootDir + "\\" + fileN, FileMode.Create, FileAccess.Write);
NetworkStream nfs = new NetworkStream(sock);
long size = int.Parse(fileS);
long rby = 0;
try
{
while (rby < size)
{
byte[] buffer = new byte[1024];
int i = nfs.Read(buffer, 0, buffer.Length);
fout.Write(buffer, 0, (int)i);
rby = rby + i;
}
fout.Close();
}
catch (Exception ed)
{
Console.WriteLine("A Exception occured in file transfer" + ed.ToString());
MessageBox.Show(ed.Message);
}
}
After the 1st download button click, files downloaded to client successfully, then I deleted all files downloaded, then I clicked the download button 2nd time, but this time it didn't work.
Files weren't got downloaded. I tried debugging, it didn't show any error, but the client application stopped at the step receiving the string listFiles from server. I mean client sended string re ok. server received string re ok. server sended string listFiles ok. but client didn't get listFiles. Does anyone know why it doesn't work? thanks for your help in advance.
Here is the code for the sendComment method, it's the same for both client and server app.
public void sendComment(string comment)
{
Socket serversock = serversocket;
if (serversock == null)
{
MessageBox.Show("Client not connected", "Connect Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
byte[] b = System.Text.Encoding.ASCII.GetBytes(comment + " ");
serversock.Send(b, b.Length, 0);
}
I don't upload the server side code because I don't think there's any problem with it and this post would be a bit long, but if you need just say and I will post it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我刚刚自己解决了这个问题。实际上,我只是构建解决方案而不是运行调试,服务器和客户端应用程序都工作正常。这个问题似乎只有当我尝试调试时才会出现。也许这是 Visual Studio 的错误,或者我的代码中的某些内容阻止了调试。
I just solved this on my own. Actually, I just build the solution instead of running debug and both server and client app work fine. The problem seems to rise only when I try debugging. Maybe it's a Visual Studio bug or there's something in my code prevent the debug.