Version 2 of The simplest possible socket demonstration

Updated 2006-01-23 00:08:40

AMG: It's not too hard.

In this example there are two computers, client and server. The client's IP address is, let's say, 10.0.0.1. It will connect to the server (IP: 10.0.0.2) on TCP port 12345. Here's the code each side runs:

Client (IP: 10.0.0.1)

 set chan [socket 10.0.0.2 12345]         ;# Open the connection
 puts $chan hello                         ;# Send a string
 flush $chan                              ;# Flush the output buffer
 puts "10.0.0.2:12345 says [gets $chan]"  ;# Receive a string
 close $chan                              ;# Close the socket

Server (IP: 10.0.0.2)

 proc accept {chan addr port} {           ;# Make a proc to accept connections
     puts "$addr:$port says [gets $chan]" ;# Receive a string
     puts $chan goodbye                   ;# Send a string
     close $chan                          ;# Close the socket (automatically flushes)
 }                                        ;#
 socket -server accept 12345              ;# Create a server socket
 vwait forever                            ;# Enter the event loop

Of course the server should already be up and running before the client starts.

What does it look like?

Client (IP: 10.0.0.1)

 10.0.0.2:12345 says goodbye

Server (IP: 10.0.0.2)

 10.0.0.1:49100 says hello

Discuss.


[ Category Tutorial | Category Networking ]