我正在开发一个从一端系统(Client Class)到另一端系统(Server Class)的文件发送应用程序,目前我正在同一台PC上测试它。
我能够将文件从客户端传输到服务器,但问题在于服务器上正在接收的该文件的扩展名。现在为了解决这个问题,我使用了一个字符串变量来存储客户端中的扩展类型通过引用客户端类,我可以在服务器类中使用该变量。
现在的问题是,
当我在服务器类中使用变量(cl.extension)时,它不返回任何值。
客户类代码
namespace Client_App
{
public partial class Clients : Form
{
public string extension;
//Create the instance of TcpClient Class so that we can use the methods and properties of that class
TcpClient clientsocket = new TcpClient();
public Clients()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//It connect client to the specified server with the ip address and the port number
//By here the server replies that the connection has been established after executing the next statement
clientsocket.Connect("127.0.0.1", 8888);
label2.Text = "From Server: Connected ";
}
private void button1_Click(object sender, EventArgs e)
{
//Here GetStream method send the message to the server
NetworkStream serverStream = clientsocket.GetStream();
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
ofd.AddExtension = true;
string filename = ofd.FileName;
byte[] outStream = File.ReadAllBytes(filename);
//Variable that store the extension of file
extension = Path.GetExtension(filename);
serverStream.Write(outStream , 0, outStream.Length);
textBox2.Text = "File has been sended to server";
serverStream.Flush();
}
}
}
服务器类代码
using Client_App;
public partial class Server : Form
{
Clients cl = new Clients();
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = new TcpClient();
public Server()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
serverSocket.Start();
clientSocket = serverSocket.AcceptTcpClient();
NetworkStream serverStream = clientSocket.GetStream();
byte[] inStream = new byte[69000];
serverStream.Read(inStream, 0, clientSocket.ReceiveBufferSize);
//After reading the stream, it give user ability to save that stream by creating a file
SaveFileDialog sfd = new SaveFileDialog();
sfd.ShowDialog();
DicrectoryBox.Text = sfd.FileName + cl.extension;//Here is problem
MessageBox.Show(cl.extension);//It does not show the extension (of client file)
File.WriteAllBytes(DicrectoryBox.Text, inStream);
StatusBox.Text = "Writing Completed";
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
clientSocket.Close();
serverSocket.Stop();
}
}
问题在于服务器类中的cl.extension,MessageBox没有显示已被客户端打磨的文件的扩展名。