Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Introduction to Socket Programming
CS 4450
What is a Socket?
• A socket is a method for accomplishing inter-process
communication (IPC)
▪ Allows one process to communicate with another process on the 
same or different machine
2
P1 P2
Socket-1 Socket-2
P1
Socket-1
P2
Socket-2
Network
Operations on a Socket
• Socket works very similar to a file
• open() socket()  -- open a socket
• read() -- read from a socket (analogous to receive data)
• write() -- write to a socket (analogous to send data)
• close() -- close the socket
3
Where does Socket fit in the Network Stack?
4
Application
Transport
Network
Data Link
Physical
Send
buffer
Receive
buffer
Userspace
Kernel
NIC
write() read()
SO
C
K
E
T
socket() close()
Blocking and Non-blocking Sockets
• By default read() and write() operations are 
blocking
• Function does not return until the operation is complete
• read() blocks until there is some data available in the 
receive buffer
• When does write() block?
• When the send buffer is full
5
Blocking and Non-blocking Sockets
• Non-blocking read() and write() return 
immediately
• read()
• If there is some data in receive buffer, read() succeeds and 
returns the amount of data read
• If the receive buffer is empty, read() returns the ERROR code
• write()
• If there is some space available in the send buffer, write() 
succeeds and returns the amount of data written
• If the send buffer is full, write() returns the ERROR code
6
Client-Server Model
7
SERVER
C
LI
EN
T 
1
C
LI
EN
T 
2
C
LI
EN
T 
3
C
LI
EN
T 
4
23.45.67.12 46.41.57.42
93.35.17.14 53.35.17.15
123.20.20.10
1 2
1 2
1 2
1 2
1 2
3004 3005
3010 3004
3005 3204
3004 3028
80 22
Well known ports
that clients connect to
Port numbers
assigned by OS
??
Two traditional modes of communication
• Connection-oriented Communication
• Establish a logical or physical connection before exchanging data
• Connectionless Communication
• Start exchanging data without any prior arrangements between 
endpoints
8
Handshake
Data exchange
Client-Server Model - APIs
9
• Connection-oriented protocol (TCP-suite)
socket()
bind()
listen()
accept()
read()
write()
socket()
connect()
write()
read()
SERVER CLIENT
Block until client 
requests connection
(if blocking socket)
Client-Server Model - APIs
10
• Connectionless protocol (UDP-suite)
socket()
bind()
recvfrom
sendto
socket()
sendto()
read()
SERVER CLIENT
Questions?
11
Demos
12
Thank you!
13