private void button1_Click(object sender, EventArgs e)
{
TcpClient joao = new TcpClient("localhost", Convert.ToInt32(25565));
MessageBox.Show(joao.Client.LocalEndPoint.ToString());
NetworkStream ns = joao.GetStream();
byte[] outbytes = Encoding.ASCII.GetBytes(textBox1.Text);
ns.Write(outbytes, 0, outbytes.Length);
richTextBox1.AppendText("Sent : " + Encoding.ASCII.GetString(outbytes));
ns.Close();
joao.Close();
}
So, this is the code i wrote for ac# client. The problem is that the output of the messageBox is "127.0.0.1:52296" and it keeps changing as i send more messages to the server. Shouldn't it be "127.0.0.1:25565" ? When i try to do it over internet it doesnt't work
When you initialize TcpClient with address and port, you specify the host you want to connect to: MSDN link
So your destination host's port will always be 25565, but the port the client uses to reach the host can vary (chooses randomly an available port).
By checking out definition of the TcpClient() overload you are using, you define the destination port as 25565 , means you connect to that remote port.
The Client
object you are echoing is in reality is a Socket
which has a property object called LocalEndPoint
. Now that you could ask this EndPoint
object about its Port
.
About why the given EndPoint.Port
keeps changing:
It's sort of about how the TCP stack works, if you don't reuse that socket it will keep changing, it's normal.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.