Reputation: 844
I've simple chat with Windows Forms Application. I'm using sockets and when I trying to connect my local IP, everything goes correctly and I can send messages locally.
But when I'm trying to connect to my friend machine with external IP nothing happens. I enter his external IP on IP field, pressed connect and program has stopped working.
Question is: what do I write in IP field? do I need more information to connect my friend's machine? I'm beginner at network programming and please help me.
Also if you could, please advice me a good book about network programming in C#.
Here is my windorm picture:
Here is my code:
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)
{
}
}
}
Upvotes: 1
Views: 1920
Reputation: 243
You need to open the remote port on your friend's computer firewall.
Upvotes: 2