views:

400

answers:

1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace PDMS_TCG
{
    public partial class FormHost : Form
    {
        public FormHost()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            {
                IPAddress ipAd = IPAddress.Parse(txtAddress.Text);

                TcpListener myList = new TcpListener(ipAd, int.Parse(txtPort.Text));

                myList.Start();
                Socket s = myList.AcceptSocket();
                RPS rps = new RPS();
                rps.Show();            
            }
        }

        private void btnHost_Click(object sender, EventArgs e)
        {
            IPAddress ipAd = IPAddress.Parse(GV.strAddress);
            TcpListener myList = new TcpListener(ipAd, int.Parse(txtPort.Text));

            myList.Start();

            Socket s = myList.AcceptSocket();
        }
    }
}

txtAddress = IP Address of Host

txtPort = Port Number

I have some confusion in terms of TcpListener/Sockets. Could someone help me fix this code? Clicking btnHost let's you host the connection and btnConnect connects to the host. Also, once connected, how can I have 1 event trigger an event on the other computer?

+3  A: 
  • Use a TcpClient on the client-side to initiate a connection to the server (Connect).

  • Use a TcpListener on the server-side to accept incoming connections (AcceptTcpClient). AcceptTcpClient returns a TcpClient.

Then call GetStream on the two TcpClients to get a Stream that you can use to communicate with the other side (synchronously or asynchronously).

Both TcpClient and TcpListener have extensive examples in the MSDN. Have a look at them and you'll have something running pretty soon.

dtb