Overview

1. What is Socket Programming

  1. Literal Meaning of Socket
    The word “socket” originally refers to an electrical outlet. An outlet creates a connection between two ends, so in network programming, it denotes an endpoint for network‑based communication.
  2. Definition of Socket Programming
    Data exchange between multiple hosts implemented with the TCP / UDP network protocols.
  3. Plain‑language Explanation
    Write code that lets two or more computers send and receive data from one another. A typical real‑world example would be a local‑area‑network chat application.

Analogy: Electrical outlet = network endpoint; plug = remote host; plugging in = establishing a network connection.

To help you grasp these concepts, we will walk through hands‑on implementation with a practical example.

2. Design for a Simple Chat Tool

Architecture Model: Client‑Server (C/S)
  • Server
  1. Bind to a specified local port and keep listening for incoming network connections
  2. Wait for connection attempts from other computers
  3. Open a communication channel once a client has connected
  • Client
    Initiate a connection by supplying the server’s IP address and port number
  • Communication Goal: Enable real‑time text messaging between two computers for instant chat functionality

Workflow

  1. Server starts up → begins port listening
  2. Client starts up → connects to server IP and port
  3. Once the connection succeeds, both sides send and receive messages

Below is a minimal working sample

Server

// 1. Instantiate TcpListener to listen on IP and port
TcpListener listener = new TcpListener(IPAddress.Any, 8899);
listener.Start();
// 2. Await incoming client connection
TcpClient client = await listener.AcceptTcpClientAsync();
// 3. Acquire network stream for message read‑write loop
NetworkStream stream = client.GetStream();
Code language: JavaScript (javascript)

Client

// Connect to target server IP and port
TcpClient client = new TcpClient();
await client.ConnectAsync("192.168.1.100",8899);
NetworkStream stream = client.GetStream();Code language: JavaScript (javascript)

Overview

Leave a Reply

Your email address will not be published. Required fields are marked *