gpt4 book ai didi

c# - C#。使用套接字和外部IP与 friend 联系

转载 作者:行者123 更新时间:2023-12-03 11:59:57 27 4
gpt4 key购买 nike

我已经与Windows Forms Application进行了简单的聊天。我正在使用套接字,当我尝试连接本地IP时,一切正常,并且可以在本地发送消息。

但是,当我尝试使用外部IP连接到我的 friend 计算机时,什么也没发生。我在IP字段上输入了他的外部IP,按了connect,程序已停止工作。

问题是:我在IP字段中写什么?我需要更多信息来连接 friend 的机器吗?我是网络编程的初学者,请帮助我。

另外,如果可以的话,请给我推荐一本有关C#网络编程的好书。

这是我的windorm图片:

这是我的代码:

namespace Client
{
public partial class Client : Form
{
public Socket ServerSocket, ClientSocket, ClientSocket2;
byte[] Buffer;

public Client()
{
InitializeComponent();
StartConnect();
}

private void StartConnect()
{
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ServerSocket.Bind(new IPEndPoint(IPAddress.Any, Convert.ToInt32(textBox2.Text)));
ServerSocket.Listen(0);

ServerSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}

private void AcceptCallback(IAsyncResult ar)
{
ClientSocket2 = ServerSocket.EndAccept(ar);
Buffer = new byte[ClientSocket.SendBufferSize];
ClientSocket2.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}

private void ReceiveCallback(IAsyncResult ar)
{
ClientSocket2.EndReceive(ar);
string Text = Encoding.ASCII.GetString(Buffer);
AppendRichTextBox(Text);

ClientSocket2.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}

private void AppendRichTextBox(string Text)
{
MethodInvoker Invoker = new MethodInvoker(delegate
{
richTextBox2.Text += "Client says: " + Text;
});

this.Invoke(Invoker);
}

private void button1_Click(object sender, EventArgs e)
{
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

ClientSocket.BeginConnect(new IPEndPoint(IPAddress.Parse(textBox1.Text), Convert.ToInt32(textBox2.Text)), new AsyncCallback(ConnectCallback), null);
}

private void ConnectCallback(IAsyncResult ar)
{
button2.Enabled = true;
ClientSocket.EndConnect(ar);
}

private void button2_Click(object sender, EventArgs e)
{
Buffer = Encoding.ASCII.GetBytes(richTextBox1.Text);
ClientSocket.BeginSend(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(SendCallback), null);
richTextBox1.Clear();
}

private void SendCallback(IAsyncResult ar)
{
ClientSocket.EndSend(ar);
}

private void Client_KeyPress(object sender, KeyPressEventArgs e)
{
}

private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar==(char)13)
{
button2_Click(sender, (EventArgs)e);
}
}

private void Client_Load(object sender, EventArgs e)
{

}
}
}

最佳答案

您需要打开 friend 计算机防火墙上的远程端口。

关于c# - C#。使用套接字和外部IP与 friend 联系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31098027/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com