C# 套接字通信在同一台机器上工作,但不能在不同的机器之间工作

C# 套接字通信在同一台机器上工作,但不能在不同的机器之间工作,c#,C#,我编写了一个客户端/服务器应用程序来发送文件。如果服务器和客户端在同一台机器上,它就可以工作,但是当我把服务器放在另一台机器上时,当服务器读取套接字时,我会出错 这是服务器的代码: class conexion { int sizeofonpacket = 9999; string filsc=""; string titre = ""; bool sendfilcomand = false; int conteur1 = 0; int conte

我编写了一个客户端/服务器应用程序来发送文件。如果服务器和客户端在同一台机器上,它就可以工作,但是当我把服务器放在另一台机器上时,当服务器读取套接字时,我会出错

这是服务器的代码:

class conexion
{
    int sizeofonpacket = 9999;
    string filsc="";
    string titre = "";
    bool sendfilcomand = false;
    int conteur1 = 0;
    int conteur2 = 0;
    BinaryWriter sf;
    TcpListener listiner;
    TcpClient client;
    NetworkStream netStream;

    public conexion(IPAddress ip, int port)
    {
        listiner = new TcpListener(ip, port);
        listiner.Start();
        client = listiner.AcceptTcpClient();
        netStream = client.GetStream();
        Console.Write("client is present \r\n ");
    }

    public void read()
    {
        while (client.Connected)
        {
            string returndata;
            int size = 0;
            string c = "";
            byte[] bs = new byte[4];
            byte[] b = new byte[1];

            try
            {
                //read the comand of client "s" for string or "b" for binary file if it is "s" it read the string that client write
                //if it is "b" we read the string "dfgjsdgfjdsgfjhdsgfj" it is not important 
                Console.Write("ready \r\n ");
                netStream.Read(b, 0, 1);

                c = Encoding.UTF8.GetString(b);
                Console.WriteLine("\r\n comand  :" + c);
                b = new byte[4];
                netStream.Read(b, 0, 4);
                returndata = Encoding.UTF8.GetString(b);
                size = Int32.Parse(returndata);
                Console.WriteLine("\r\n size de packet int =" + size);
                b = new byte[size];
                netStream.Read(b, 0, size);
            }
            catch
            {
                Console.WriteLine("\r\n conexion echoue");
                listiner.Stop();
            }

            switch (c)
            {
                case "b":
                    if (sendfilcomand == false) //if sendfilcomand is false we read first the title
                    {
                        sendfilcomand = true;

                        break;
                    }
                    sendfilcomand = false;
                    filsc = titre;
                    Console.WriteLine("\r\nle titr est:" + titre);

                    titre = "";
                    sf = new BinaryWriter(new FileStream(filsc, FileMode.Create));

                    conteur2 = 0;
                    conteur1 = size;
                    crebfile(b);
                    Console.WriteLine("\r\n creat file for " + conteur2 + " to " + conteur1);
                    b = new byte[sizeofonpacket];
                    while (size != 0)
                    {
                        try
                        {
                            netStream.Read(bs, 0, 4);

                            returndata = Encoding.UTF8.GetString(bs);
                            size = Int32.Parse(returndata);

                            conteur1 = size;
                            Console.WriteLine("sizee a get" + size);

                            if (size == 0)
                            {
                                Console.WriteLine("yout est termine");
                                sf.Close();
                                conteur1 = 0;
                                conteur2 = 0;
                                break;
                            }
                            else if (size != sizeofonpacket)
                            {
                                b = new byte[size];
                            }
                            netStream.Read(b, 0, size);
                        }
                        catch 
                        {
                            Console.WriteLine("\r\n imposible to read ");
                        }

                        crebfile(b);
                        b.Initialize();
                    }

                    sf.Close();
                    conteur1 = 0;
                    conteur2 = 0;
                    break;

                case "s":
                    returndata = Encoding.UTF8.GetString(b);
                    Console.WriteLine("\r\n" + returndata);

                    if (sendfilcomand)
                    {
                        titre = returndata;
                        Console.WriteLine("titre a get" + titre);

                        break;
                    }
                    break;

                default:
                    Console.WriteLine("\r\n rien comand");
                    break;
            }
        }
    }

    public string quadripl(string s)
    {
        while (s.Length < 4)
        {
            s = "0" + s;
        }
        return s;
    }

    public void crebfile(byte[] byts)
    {
        try
        {
            sf.Write(byts, 0, conteur1);
        }
        catch
        {
            Console.WriteLine("imposible de crer le fichier");
        }
    }
}
类连接
{
int-sizeofonpacket=9999;
字符串filsc=“”;
弦滴度=”;
bool sendfilcomand=假;
int conteur1=0;
int conteur2=0;
二元书写;
TcpListener-listiner;
TCP客户机;
网络流;
公用连接(ip地址ip,int端口)
{
listiner=新的TcpListener(ip,端口);
Start();
client=listiner.AcceptTcpClient();
netStream=client.GetStream();
Console.Write(“客户端存在\r\n”);
}
公共无效读取()
{
while(client.Connected)
{
字符串返回数据;
int size=0;
字符串c=“”;
字节[]bs=新字节[4];
字节[]b=新字节[1];
尝试
{
//读取客户端“s”的命令作为字符串,或“b”作为二进制文件,如果是“s”,则读取客户端写入的字符串
//如果是“b”,则读取字符串“DFGJSDGFJDSGFJHDSGJ”,这并不重要
控制台。写入(“就绪\r\n”);
netStream.Read(b,0,1);
c=Encoding.UTF8.GetString(b);
Console.WriteLine(“\r\n命令:“+c”);
b=新字节[4];
netStream.Read(b,0,4);
returndata=Encoding.UTF8.GetString(b);
size=Int32.Parse(返回数据);
Console.WriteLine(“\r\n size de packet int=“+size”);
b=新字节[大小];
netStream.Read(b,0,size);
}
接住
{
Console.WriteLine(“\r\n conexion echoue”);
listiner.Stop();
}
开关(c)
{
案例“b”:
if(sendfilcomand==false)//如果sendfilcomand为false,我们首先读取标题
{
sendfilcomand=true;
打破
}
sendfilcomand=false;
filsc=滴度;
Console.WriteLine(“\r\nle titr est:“+titre”);
titre=“”;
sf=新的二进制编写器(新的文件流(filsc,FileMode.Create));
conteur2=0;
conteur1=大小;
crebfile(b);
Console.WriteLine(“\r\n为“+conteur2+”到“+conteur1”创建文件);
b=新字节[SizeFonPacket];
while(大小!=0)
{
尝试
{
netStream.Read(bs,0,4);
returndata=Encoding.UTF8.GetString(bs);
size=Int32.Parse(返回数据);
conteur1=大小;
Console.WriteLine(“sizee a get”+size);
如果(大小==0)
{
Console.WriteLine(“yout est termine”);
sf.Close();
conteur1=0;
conteur2=0;
打破
}
else if(大小!=SizeFonPacket)
{
b=新字节[大小];
}
netStream.Read(b,0,size);
}
接住
{
Console.WriteLine(“\r\n无法读取”);
}
crebfile(b);
b、 初始化();
}
sf.Close();
conteur1=0;
conteur2=0;
打破
案例“s”:
returndata=Encoding.UTF8.GetString(b);
Console.WriteLine(“\r\n”+返回数据);
如果(发送FILCOMAND)
{
titre=返回数据;
Console.WriteLine(“titre a get”+titre);
打破
}
打破
违约:
Console.WriteLine(“\r\n rien comand”);
打破
}
}
}
公共字符串QUARIPL(字符串s)
{
而(s.长度<4)
{
s=“0”+s;
}
返回s;
}
公共无效crebfile(字节[]byts)
{
尝试
{
sf.Write(byts,0,conteur1);
}
接住
{
控制台。WriteLine(“不可能的crer le fichier”);
}
}
}
以下是客户端代码:

class conexion
{
    string filsr;
    int sizeofonpacket = 9999;
    bool sendfilcomand = false;
    bool getfilcomand = false;
    int bali;
    int fali;
    Stream file;
    TcpListener listiner;
    TcpClient client;
    NetworkStream netStream;

    public conexion(string ip, int port)
    {
        listiner = null;
        Console.Write("star client ");
        client = new TcpClient(ip, 3568);
        netStream = client.GetStream();
    }

    public void send()
    {
        while (client.Connected)
        {
            //enter the comand "s" or "b"
            string c = "";
            Console.WriteLine("\r\n ecrir comand:");
            c = Console.ReadLine();

            string s = "";
            if (c == "s")
            {
                Console.WriteLine("\r\n entrer string:");
                s = Console.ReadLine();
            }
            string size = "";
            Byte[] sendBytes = null;
            //try
            {
                switch (c)
                {
                    case "b":
                        Console.WriteLine("\r\n comand binary file");
                        netStream.Write(Encoding.UTF8.GetBytes(c), 0, 1);
                        if (sendfilcomand == false) //we will first send the patsh of file after we will send data of file
                        {
                            sendBytes = Encoding.UTF8.GetBytes("dfgjsdgfjdsgfjhdsgfj"); //this is not important
                            size = quadripl(sendBytes.Length.ToString());
                            netStream.Write(Encoding.UTF8.GetBytes(size), 0, Encoding.UTF8.GetBytes(size).Length);
                            netStream.Write(sendBytes, 0, sendBytes.Length);
                            sendfilcomand = true;
                            s = getitr();
                            c = "s";
                            goto case "s";
                        }
                        sendfilcomand = false; //now we will send data
                        filsr = actitr(); //the title is save in "C:/Users/Ce-Pc/Desktop/titreactuel.txt"
                        file = new FileStream(filsr, FileMode.Open);
                        fali = (int)file.Length;
                        bali = 0;
                        byte[] bs = new byte[4];
                        Console.WriteLine("\r\n star sending ");
                        do
                        {

                            sendBytes = filebtobyte(filsr); //read part of file to send
                            Console.WriteLine("\r\n terminer " + bali + " " + " " + fali);
                            size = quadripl(sendBytes.Length.ToString()); //just for add the zero
                            Console.WriteLine("\r\n le size de fichier binair est " + size);
                            netStream.Write(Encoding.UTF8.GetBytes(size), 0, Encoding.UTF8.GetBytes(size).Length);

                            netStream.Write(sendBytes, 0, sendBytes.Length);

                        } while (bali != -1); //when we come to last part of the file (filebtobyte give -1 to bali)
                        bali = 0;
                        size = quadripl("0");
                        Console.WriteLine("\r\n terminer fiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiin ");
                        netStream.Write(Encoding.UTF8.GetBytes(size), 0, Encoding.UTF8.GetBytes(size).Length);
                        netStream.Read(bs, 0, 4);
                        break;
                    case "s":
                        Console.WriteLine("\r\n comand string");
                        netStream.Write(Encoding.UTF8.GetBytes(c), 0, 1);
                        size = quadripl(s.Length.ToString());
                        sendBytes = Encoding.UTF8.GetBytes(size);
                        Console.WriteLine("\r\n size=" + size);
                        netStream.Write(sendBytes, 0, sendBytes.Length);
                        sendBytes = Encoding.UTF8.GetBytes(s);
                        netStream.Write(sendBytes, 0, sendBytes.Length);

                        if (sendfilcomand)
                        {
                            c = "b";
                            goto case "b";
                        }
                        break;
                    default:
                        Console.WriteLine("\r\n rien comand");
                        break;
                }
            }
            catch
            {
                Console.WriteLine("\r\n imposible de transfer");
            }
        }
        Console.Write("client est deconect \r\n ");
    }

 //////////////////the functions//////////////////////////////////

    public byte[] filebtobyte(string s)
    {
        byte[] byts = null;
        try
        {
            if (fali - bali < sizeofonpacket)
            {
                byts = new byte[fali - bali];
                file.Read(byts, 0, fali - bali);
                file.Close();
                bali = -1;
            }
            else
            {
                byts = new byte[sizeofonpacket];
                file.Read(byts, 0, sizeofonpacket);
                bali += sizeofonpacket;
            }
        }
        catch
        {
            Console.WriteLine("imposible de trouver le fichier");
        }
        return byts;
    }
    public string quadripl(string s)
    {
        while (s.Length < 4)
        { s = "0" + s; }
        return s;
    }

    public string getitr()
    {
        StreamReader titrfil = new StreamReader("C:/Users/Ce-Pc/Desktop/titre.txt");
        string sss = "";
        try
        {
            sss = titrfil.ReadLine();
            Console.WriteLine("\r\n le chemin " + sss);
            titrfil.Close();
        }
        catch
        {
            Console.WriteLine("\r\n imposible");
        }
        return sss;
    }
    public string actitr()
    {
        StreamReader titrfil = new StreamReader("C:/Users/Ce-Pc/Desktop/titreactuel.txt");
        string sss = "";
        try
        {
            sss = titrfil.ReadLine();
            Console.WriteLine("\r\n le chemin " + sss);
            titrfil.Close();
        }
        catch
        {
            Console.WriteLine("\r\n imposible");
        }
        return sss;
    }
}
类连接
{
弦丝;
int-sizeofonpacket=9999;
bool sendfilcomand=假;
bool getfilcomand=false;
巴厘岛国际酒店;
int fali;
流文件;
TcpListener-listiner;
TCP客户机;
网络流;
公用连接(字符串ip,int端口)
{
listiner=null;
Console.Write(“明星客户机”);
客户=新的TCP客户(ip,3568);
netStream=client.GetStream();
}
公共无效发送()
{
while(client.Connected)
{
//输入comand“s”或“b”
字符串c=“”;
Console.WriteLine(“\r\n ecrir comand:”);
c=Console.ReadLine();
字符串s=“”;
如果(c=“s”)
{
Console.WriteLine(“\r\n输入字符串:”);
s=控制台。Re
telnet <server ip> 3568
static void sendMessage(string c_1)
    {
        byte[] command = Encoding.ASCII.GetBytes(c_1);
        byte[] commandLength = Encoding.ASCII.GetBytes(command.Length.ToString());
        List<byte> commandLengthInByteArray = commandLength.ToList();
        while (true)
        {
            if (commandLengthInByteArray.ToArray().Length < 50)
            {
                commandLengthInByteArray.Add(Convert.ToByte('x'));
            }
            else
            {
                break;
            }
        }
        byte[] parsedCommandLength = commandLengthInByteArray.ToArray();
        sck.Send(parsedCommandLength);
        sck.Send(command);
    }
    static void sendMessage_ftp(byte[] data)
    {
        byte[] commandLength = Encoding.ASCII.GetBytes(data.Length.ToString());
        List<byte> commandLengthInByteArray = commandLength.ToList();
        while (true)
        {
            if (commandLengthInByteArray.ToArray().Length < 50)
            {
                commandLengthInByteArray.Add(Convert.ToByte('x'));
            }
            else
            {
                break;
            }
        }
        byte[] parsedCommandLength = commandLengthInByteArray.ToArray();
        sck.Send(parsedCommandLength);
        sck.Send(data);
    }

static byte[] getResponse(Socket sck)
    {
        byte[] CommandLengthInByteArray = ReadBytes(50, sck);
        List<byte> commandLengthInByteArrayList = new List<byte>();
        foreach (byte b in CommandLengthInByteArray)
        {
            if (b.ToString() != "120")
            {
                commandLengthInByteArrayList.Add(b);
            }
        }
        Int32 fileSize = Convert.ToInt32(Encoding.ASCII.GetString(commandLengthInByteArrayList.ToArray()));
        byte[] data = ReadBytes(fileSize, sck);
        return data;
    }
    static byte[] ReadBytes(Int32 size, Socket sck)
    {
        //The size of the amount of bytes you want to recieve, eg 1024
        var bytes = new byte[size];
        Int32 total = 0;
        do
        {
            var read = sck.Receive(bytes, total, size - Convert.ToInt32(total), SocketFlags.None);
            if (read == 0)
            {
                //If it gets here and you received 0 bytes it means that the Socket has Disconnected gracefully (without throwing exception) so you will need to handle that here
            }
            total += read;
            //If you have sent 1024 bytes and Receive only 512 then it wil continue to recieve in the correct index thus when total is equal to 1024 you will have recieved all the bytes
        } while (total != size);
        return bytes;
    }