socket programmer

csharp Jordan
  • 14 years ago

    hi

    i want to ask of how to connect my pc through net to another pc

  • 14 years ago
    The 2003 101 Samples from Microsoft includes a client/server chat application as an example of using sockets.

  • 14 years ago

    Hi,

    you can connect two PC as client-server or as peer-to-peer using any language as C++ and C#.

    i can help you in C#.

     you can use one computer to begin connection and the other listen the connection.

    use this classes and create objects as follows:

    BinaryReader    reader;

    BinaryWriter    writer;

    Socket    connection;

    NetworkStream    socketStream;

    Thread    readThread;

    you must call the function as thread in the default constructor as follows:

    readThread = new Thread(new ThreadStart(FunctionName));

    readThread.Start();

    use TcpListener class and create an object to listen to connection as follows:

    TcpListener listener;

    listener = new TcpListener(5000);     ///5000 the port number you can use any other port number

    to begin listening to connection:

    listener.Start();

    then write this code to accept connection:

    while(true)

    {

    connection = listener.AcceptSocket();

    socketStream = new NetworkStream(connection);

    writer = new BinaryWriter(socketStream);

    reader = new BinaryReader(socketStream);

    string Reply = "";

    do {

    try{

    Reply = reader.ReadString();

    }

    catch(Exception)

    {

    break;

    }

    }while(Reply!="Terminate"&&connection.Connected)

    writer.Close();

    reader.Close();

    socketStream.Close();

    connection.Close();

    }

    waiting connection as follows:

    TcpClient client;

    client = new TcpClient();

    client.Connect("localhost",5000);  //5000 the port number, replace localhost by IP address for the other computer

    socketStream = client.GetStream();

    writer = new BinaryWriter(socketStream);

    reader = new BinaryReader(socketStream);

    do{

    try{

    string message = reader.ReadString();  //contain the message from the other peer;

    }

    catch()

    {}

    }while(message!="Terminate");

    writer.Close();

    reader.Close();

    socketStream.Close();

    client.Close();

     

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.” - Rich Cook