صفحه 1:
ام ۱
connecting processes
ا۳) سمل
doc
صفحه 2:
ل ا ةا
rn a وروت OI Cn ng AO)
Progra Ole Server ta C ©
SE ea a AOL a ela aR Pac)
* RePerewes
صفحه 3:
مرب هم میا
صفحه 4:
او موه و سم موه وا
ae ee Cee ecco en nee eee
میب
nO eco Ceo e eea
cee emote os
Oh cee ene tee ere
eam een hace aac
eed 00
ومسا بجت ae 2
را
سوس سكام عمجو | الحصور
SERVER
صفحه 5:
SO one eee
00 Ener
PO Read
BR (Creme ا ا ا cee cE) emer
بل
تست ۱
صفحه 6:
0 tnd
| heirs eter ec creme ec arc]
RRC UNCC enteeek O(n entree oe eeetetemere bara]
RCO Rea aC COR Tae ao ae ee
Dacre
Re oe Ce eo)
ee eed eee eet ool eee)
2 ee er)
۳ ood
صفحه 7:
(Ng AOL a و as al
صفحه 8:
Beer reer a)
SC Ree ne ee
= Orede o POP socket
SO 3/2 (سسسوج نجه لوخ
eee enero ee
۳ eter
See ance arog
SC Reece ne لوتصجد خأن مصتاسيب
ore ne wearer a]
ا ا لي هیا ات مت ۱۳
eee رن
SOR ee a ee a
ee ee ee ب يي ل
0 و
0 0 te
صفحه 9:
[7 ل سينيد
۱
۳
|
pee too
لوصوو 00000 تا رت ۱
۱
ل 0 5
ا اي رس ریس مر او سس 3
pec
eC Rec ee ee cd
RO ed ne
صفحه 10:
eat ea AO, a mela 4
صفحه 11:
See فص
:سحام
|
Se ee
ل
Se ee Re Rn as
Sn eee ene eg
:سحام
SO ee oe ed
0 ee Ee RE
socket oa the leteraet, oc okdess copies of a pot cacber oa the host
ان
See
Sn ee cca ee ed
Re a oo
Cd
صفحه 12:
۱۱ esisas rs il Ox Or ac OF
Client.c a structure to contain an internet addre:
[0 defined in the include file <netinet/in.h
#include <sys/types.h> CAEN G
a eS aes
اكناباء وتاعم> عفبااء مزع
eae esc Ne in_addr
ero[8]; /* not used, must
* should be AF_INET
void error(char *msg){ _perror(msg); _exit(0);}
fae ی Uae VOLE naar
eee Aaa 1
]عناتاو 506۵00۲16 56۳۷۵00۲:
Bea eae tesa
تین توت
{ )3 و
2 ل 00
exit(0);
1
0
0 LCL
۱۱3 یت opening socket
صفحه 13:
۱۱ esisas rs il Ox Or ac OF
Client.c Socket System Call - create an end point for
#include <stdio.h>
Easel ee [of ae
#include <sys/socket.h>
#include <netinet/in.h>
ل ان teo Mabe
void error(char *msg){ _perror(msg);
fae ی Uae VOLE
eee Aaa
۱ :لكر e.g. IPPROTO_UDP, IP
Pea ee tec
تین توت
fies a parti
if (arge < 3) {
رت ا
aca ت۱9
صفحه 14:
۱۱ esisas rs il Ox Or ac OF
Client.c
0
if (server == NULL) { fprintf(stderr,"ERROR, no such host\n");
:(3000_نمع ف ۱ :(0ه
0 ۱
1
۱۲۳
0000 ea ent
Fra Ccon teeters CRN Colac ek ))
Peete
PaO eek aaa ta e Connect System Call -jnitiat
۱۳ iCuy eee D)
0 icra eat a KO
error("ERROR writing to soc! ل
(6۲,256)انا0)اعقط
۱
if(n <0)
۱
۱
Cesena
یت
صفحه 15:
۱۱ esisas rs il Ox Or ac OF
Client.c
0
if (server == NULL) { fprintf(stderr,"ERROR, no such host\n");
:(3000_نمع ف )امع 2د ,/300_معدة (4 رهط ) )مع 2ط 1
0 ۱
1
۱۲۳
serv_addr.sin_port = htons(portno);
لي ل (oR تست و۱
:0۳06609 6۲۲۵۲)۱2۳6۵۵
تک یب تسس Mgt eser-te ععغمع عدمعام")لاماءم
ات eis یت
n= sendisockfd,buffer,strien(buffer),0); | Emam
بصن را )0 < if(n
00
ات نا
int ۳۵ 0۱
if(n <0)
ل كي lh
Pr kas Gm cto descriptor that 7
Cereal
ree
لكت
صفحه 16:
۱۱ esisas rs il Ox Or ac OF
Client.c
0
if (server == NULL) { fprintf(stderr,"ERROR, no such host\n");
:(3000_نمع ف )امع 2د ,/300_معدة (4 رهط ) )مع 2ط 1
0 ۱
1
۱۲۳
serv_addr.sin_port = htons(portno);
لي ل (oR تست و۱
:0۳06609 6۲۲۵۲)۱2۳6۵۵
Ga Rt om Mea Recy System Call
۱ ۰
۱۳ erence nice : inctu
inclu
:(8,255,0]أناط, 500110
if(n <0)
سس سس تست || Returns number of bytes te
PIG LL La descriptor that m
Cereal
یت
لكت
صفحه 17:
۱۱ esisas rs il Ox Or ac OF
Client.c
ere ureter a Ie) 08
a ted OO Melle el ا لك
1 bzero((char*) &serv_addr, sizeof(serv_addr));
Per et aed eee DCP Cr aes |e eC Rg
۱۳
serv_addr.sin_port = htons(portno);
Frater ta te ORS A pete QT) A)
error("ERROR connecting"
PG eR me Ree :ل" Slose System Call
ت۱۳ sere ame a Clg aan
0 HD include <unistd h:
if(n <0) aaa
00 nt close( int 5);
2 < ۲۵6۷ )50060,
rae)
ctiptor to be cl
eee ل ا cay
\n", buffer);
Rah تس
۲6 0:
لكت
صفحه 18:
۱
و
<.5/5/500۲6> 06/۵06[
eat tae as رز
void error(char *msg){ perror(msg); _exit(0);}
4([]بوعة* ی عوة غمأ)متهد غم
nel i ا
و
ee ا Berita sore
10
if (argc < 2) { fprintf(stderr,"ERROR, no port provided\n"); exit(1); }
رت
ieee Rage ae ater 1
bzero((char *) &serv_addr, sizeof(serv_addr));
Pease cle e0)H
eC > ۸۴ ۱۴۲:
oe Oa ۱۳
Pe Ces reac ea
صفحه 19:
۱) TOP Gerver ta O
Server.c
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) <
0) ری یت یت ien
0
ی
:(6۲,256)/ناط)۵:ععه
۱۳
if (n < 0) error("ERROR reading
Pr ae caer eee ata
0 eet
تک ی ۱۱
»أل رت
#include ۳
aren
} int bind i
صفحه 20:
۱) TOP Gerver ta O
Server.c
PAC Crs لي ل
0) 0 at
listen(sockfd,5);
0
65581 ناولا 008 ",50410ب 00)0 ع5 > م
لي ا لي CaCO) Recodo
erate
که
تست
that mu
maximum
establish
صفحه 21:
۱) TOP Gerver ta O
Server.c
PAC ine Crs tase a RS Me rom)
error("ERROR on binding");
0
00 CU
Pre a Pree ss cle teeter ae eee Cee el
figure ل etc a
۱
0 acme wet ۳
ل ten aca || eee eee
ocket
Celerra
۳ #include
aren #include
كك
صفحه 22:
]۱ ete eae ee ee ee ee
Se daatea diate hana
ee tes eek ele MOOR en Cee CUNO a
See السضا جز جد 5010_1005) 00 خا موص 1010000:01:0_)0)005/ 8 لمعيه
سوه
ی
ی( ce eee ()مسخدم امب
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
len = sizeof(struct sockaddr_in);
۱۷۱6 )1( )
۳ ۷۵
Deca ل A eas ee)
&server, len);
۱1 ton
[read */
ا زر ue
TA) ا
صفحه 23:
SN a aa ROL Gal at Od
as
/ =>
acetates ae eh earn fete ated ene ae
pete nen eee
م0 eee ool en eet Semen eve
یب
eee eed coed ا
0
aoc LV aol eM LH رم
len = sizeof(struct sockaddr_in);
while (1) {
رهز
۱6۵ ,66۲۵۲۵(* 5۵6۵۵۵۲ بای ,0 ,1024 ,ناد ۲۵۵/۲۲۵۲۵6۵ -
یی كن کی نا
یر
۱۳ تست elt La Te] NS AO eR Leake cele
ليم نسي
f (n < 0) error("sendto");
1
صفحه 24:
الا
0 قبسا سس وس 9
7a
7 تست هه ما
تم تا تسا
يي A ea
oe led em eee led
ere tenet nee ee
] de ee Ol a
TR باصا سما جا "جاا. © © لصب"
00 LCN CHESS RYT lok tak eke
1 me a eek ee KO cee
#include <winsock.h>
ال
۱
ACNE anno
هن
0000
eee ater
صفحه 25:
Ceara رسمه ۱0 Rs]
صفحه 26:
فصو مات نا ی تا تس سل
تم ما ابا ول رام ای ما
CSO eta cee ee
حا هذا
0
حك مزحت جه ed ee oa ee
واه سا(
Se ne
۱ en ea
Sd a cee oe RS eee
Resa rele
"۷
۱ ene
eae
1
remotes nee
001
1
صفحه 27:
0 ب ب ا kW
Cea aad
کش
MyServeric
رو
2
ea Molter ute
0
7
ماه مات هت ی و و تا ۱3
مات صتا مات مات سب مت تا
تام > 4116050661 506161
۷
۱
۱
((ع) اه ناه eee
3
صفحه 28:
ماه وتا
تا رگ
اما ماما مسا
Pett
ne
نعم - اناما
0
1
] (ء ومتامعء»ع0ا) لعاف
Sins oy
+
RN a ei OC ek a ee
ای تیا ee a
مر Oe eee ee eae eee
00
7 مش
eed
۱ ete leucrte a eh eit
7
catch (IOException e) {
00
+
— On the serve
the chet:
صفحه 29:
۱
0
0ك eee eee reer Cen
مصعم خا
on Se 0
0
۲ ۵ ۱0۳۵۵۱00 (عای
000
ا
از
Cate Ree Oe rca
Peon ا sy
2
Chey
Peeeco ل ا ec
/
(۵ ۱08۱00 (عای
0 |
Perc سای سا
صفحه 30:
هه ۱
0
2
۳
۱ y
ك ممتامعء»عها) ميقع
Sacer mC
1
0 a et need cas ce Ore Ot Oe Cen Rem ee aevutaa
صفحه 31:
تا
te te cen ed ce a
es
55020000008
2
Preise
:0)عدماء.أنامما
Delay
2
eNotes ۵ )
Sec :)00اه
1
۷
rose
انام ما 054):
ieee
Dives
1
em osc ك
System.out printin(e);
1
9
صفحه 32:
38 TN aa ass ROL تا وت ف
۰ 2
4
/6
ام م۱
a as a at a Rk ae 0
يي ا
try {
DatagramSocket socket = new
00
1
eae scene
Secures aan
۶
SUR er neet en ce Reem eel ae ears
Pee eee
2
eee eee eee
1
catch (IOException e) {
:درگ
1
صفحه 33:
و موه( مس مرلو و نیوا ۰
ات مها 0
0ك 8
00 Cel
InetAddress address =
eer eee en Eee ee Oy
ل
0
Peace ees
Peer aa
eee
:(0هادصاه واه هم وه ناک 6۵۱ > ۵۵۷۵۵ ee
00
:لل لقعم
ea
صفحه 34:
هم تا ۱
اما ارگ ۱
06 5
0
Pee مي rece ta
CMa
ل 00
| ee ee ee ee
int port = packet.getPort();
۱
300755 0060
Preemie
00 0و5
ee TU از
صفحه 35:
اش ماه
a يي
0 eres
SC ا
eRe ee eee ea, ve eee Coed
CN EA a tee a
eae Me eat
Dre haa Puortd — Owtrw Oriworhtog,
لوده سيفب للك :عدامدجا/عوصل امدمت. مدي مدر !صا
دين ال د ل اي
2ك ذه 1 لته STE
Socket Programming
connecting processes
Jignesh Patel
Palanivel Rathinam
Overview
• Introduction to Sockets
• A generic Client-Server application
• Programming Client-Server in C
• Programming Client-Server in Java
• References
Introduction to Sockets
Introduction to Sockets
•
Why Sockets?
– Used for Interprocess communication.
•
The Client-Server model
– Most interprocess communication uses client-server model
– Client & Server are two processes that wants to communicate with each
•
other
– The Client process connects to the Server process, to make a request for
information/services own by the Server.
– Once the connection is established between Client process and Server
process, they can start sending / receiving information.
What are Sockets?
– End-point of interprocess communication.
– An interface through which processes can
send / receive information
Socket
Introduction to Sockets
•
What exactly creates a Socket?
– <IP address, Port #> tuple
•
What makes a connection?
– {Source<IP address, Port #> , Destination <IP address, Port #>} i.e. source
socket – destination socket pair uniquely identifies a connection.
•
Example
134
3
Server
Client
192.168.
0.2
80
134
3
Client
192.168.
0.3
192.168.
0.1
54
88
Client
192.168.
0.2
Introduction to Sockets
•
Socket Types
– STREAM – uses TCP which is reliable, stream oriented protocol
– DATAGRAM – uses UDP which is unreliable, message oriented protocol
– RAW – provides RAW data transfer directly over IP protocol (no transport layer)
•
Sockets can use
– “unicast” ( for a particular IP address destination)
– “multicast” ( a set of destinations – 224.x.x.x)
– “broadcast” (direct and limited)
– “Loopback” address i.e. 127.x.x.x
A generic Client-Server application
A generic TCP application
•
algorithm for TCP client
– Find the IP address and port number of server
– Create a TCP socket
– Connect the socket to server (Server must be up and listening for new requests)
– Send/ receive data with server using the socket
– Close the connection
•
algorithm for TCP server
– Find the IP address and port number of server
– Create a TCP server socket
– Bind the server socket to server IP and Port number (this is the port to which clients
will connect)
– Accept a new connection from client
• returns a client socket that represents the client which is connected
– Send/ receive data with client using the client socket
– Close the connection with client
A generic UDP application
•
•
algorithm for UDP client
– Find the IP address and port number of server
– Create a UDP socket
– Send/ receive data with server using the socket
– Close the connection
algorithm for UDP server
– Find the IP address and port number of server
– Create a UDP server socket
– Bind the server socket to server IP and Port number (this is the port to which clients will
send)
– Send/ receive data with client using the client socket
– Close the connection with client
Programming Client-Server in C
Programming Client-Server in C
•
•
The steps involved in establishing a socket on the client side are as
follows:
– Create a socket with the socket() system call
– Connect the socket to the address of the server using the connect() system
call
– Send and receive data using send() and recv() system calls.
The steps involved in establishing a socket on the server side are as
follows:
– Create a socket with the socket() system call
– Bind the socket to an address using the bind() system call. For a server
socket on the Internet, an address consists of a port number on the host
machine.
– Listen for connections with the listen() system call
– Accept a connection with the accept() system call. This call typically blocks
until a client connects with the server.
– Send and receive data
Programming TCP Client in C
Client.c
#include
#include
#include
#include
#include
/* a structure to contain an internet address
<stdio.h>
<sys/types.h>
<sys/socket.h>
<netinet/in.h>
<netdb.h>
void error(char *msg){
perror(msg);
int main(int argc, char *argv[]){
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
exit(0);}
defined in the include file <netinet/in.h> */
struct sockaddr_in {
short sin_family; /* should be AF_INET
*/
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8]; /* not used, must be
zero */
};
struct in_addr {
unsigned long s_addr;
};
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd < 0)
error("ERROR opening socket");
Programming TCP Client in C
Client.c
#include
#include
#include
#include
#include
Socket System Call – create an end point for
communication
<stdio.h>
<sys/types.h>
<sys/socket.h>
<netinet/in.h>
<netdb.h>
void error(char *msg){
#include <sys/types.h>
#include <sys/socket.h>
int socket(int domain, int type, int protocol);
perror(msg);
int main(int argc, char *argv[]){
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
exit(0);}
Returns a descriptor
domain: selects protocol family
e.g. PF_IPX, PF_X25, PF_APPLETALK
type: specifies communication semantics
e.g. SOCK_DGRAM, SOCK_RAW
protocol: specifies a particular protocol to be
used
e.g. IPPROTO_UDP, IPPROTO_ICMP
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd < 0)
error("ERROR opening socket");
Programming TCP Client in C
Client.c
exit(0);
server = gethostbyname(argv[1]);
if (server == NULL) { fprintf(stderr,"ERROR, no such host\n");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr
, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
Connect System Call – initiates a
printf("Please enter the message: ");
connection on a socket
bzero(buffer,256); fgets(buffer,255,stdin);
n = send(sockfd,buffer,strlen(buffer),0);
#include <sys/types.h>
#include <sys/socket.h>
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
int connect( int sockfd,
n = recv(sockfd,buffer,255,0);
const struct sockaddr *serv_addr,
if (n < 0)
socklen_t addrlen);
error("ERROR reading from socket");
Returns 0 on success
printf("%s\n",buffer);
sockfd: descriptor that must refer to a socket
close(sockfd);
serv_addr: address to which we want to
return 0;
}
connect
addrlen: length of serv_addr
Programming TCP Client in C
Client.c
exit(0);
server = gethostbyname(argv[1]);
if (server == NULL) { fprintf(stderr,"ERROR, no such host\n");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr
, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
Send System Call – send a message to a
printf("Please enter the message: ");
socket
bzero(buffer,256); fgets(buffer,255,stdin);
#include <sys/types.h>
n = send(sockfd,buffer,strlen(buffer),0);
#include <sys/socket.h>
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
int send( int s, const void *msg, size_t len,
n = recv(sockfd,buffer,255,0);
int flags);
if (n < 0)
error("ERROR reading from socket"); Returns number of characters sent on success
s: descriptor that must refer to a socket in
printf("%s\n",buffer);
connected state
close(sockfd);
msg: data that we want to send
return 0;
len: length of data
}
flags: use default 0. MSG_OOB, MSG_DONTWAIT
Programming TCP Client in C
Client.c
exit(0);
server = gethostbyname(argv[1]);
if (server == NULL) { fprintf(stderr,"ERROR, no such host\n");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr
, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
Recv System Call – receive a message from a
printf("Please enter the message: ");
socket
bzero(buffer,256); fgets(buffer,255,stdin);
#include <sys/types.h>
n = send(sockfd,buffer,strlen(buffer),0);
#include <sys/socket.h>
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
int recv( int s, const void *buff, size_t len,
n = recv(sockfd,buffer,255,0);
int flags);
if (n < 0)
error("ERROR reading from socket"); Returns number of bytes received on success
s: descriptor that must refer to a socket in
printf("%s\n",buffer);
connected state
close(sockfd);
buff: data that we want to receive
return 0;
len: length of data
}
flags: use default 0. MSG_OOB, MSG_DONTWAIT
Programming TCP Client in C
Client.c
exit(0);
server = gethostbyname(argv[1]);
if (server == NULL) { fprintf(stderr,"ERROR, no such host\n");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr
, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
Close System Call – close a socket
printf("Please enter the message: ");
descriptor
bzero(buffer,256); fgets(buffer,255,stdin);
n = send(sockfd,buffer,strlen(buffer),0);
#include <unistd.h>
if (n < 0)
error("ERROR writing to socket");
int close( int s);
bzero(buffer,256);
n = recv(sockfd,buffer,255,0);
Returns 0 on success
if (n < 0)
s: descriptor to be closed
error("ERROR reading from socket");
printf("%s\n",buffer);
close(sockfd);
return 0;
}
Programming TCP Server in C
Server.c
#include
#include
#include
#include
<stdio.h>
<sys/types.h>
<sys/socket.h>
<netinet/in.h>
void error(char *msg){
perror(msg);
exit(0);}
int main(int argc, char *argv[]){
int sockfd, newsockfd, portno, clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) { fprintf(stderr,"ERROR, no port provided\n"); exit(1); }
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
Programming TCP Server in C
Server.c
0)
}
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) <
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) error("ERROR on accept");
bzero(buffer,256);
n = recv(newsockfd,buffer,255,0);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
n = send(newsockfd,"I got your message",18,0);
if (n < 0) error("ERROR writing to socket"); Bind System Call – bind a name to a socket
close(newsockfd);
#include <sys/types.h>
close(sockfd);
#include <sys/socket.h>
return 0;
int bind( int sockfd,
const struct sockaddr * serv_addr,
socklen_t addrlen);
Returns 0 on success
sockfd: descriptor that must refer to a socket
serv_addr: address to which we want to
connect
addrlen: length of serv_addr
Programming TCP Server in C
Server.c
0)
}
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) <
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) error("ERROR on accept");
bzero(buffer,256);
n = recv(newsockfd,buffer,255,0);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
n = send(newsockfd,"I got your message",18,0);
if (n < 0) error("ERROR writing to socket"); Listen System Call – listen for connections
on a socket
close(newsockfd);
close(sockfd);
#include <sys/types.h>
return 0;
#include <sys/socket.h>
int listen( int s, int backlog);
Returns 0 on success
s: descriptor that must refer to a socket
backlog: maximum length the queue for
completely established sockets waiting to be
accepted
addrlen: length of serv_addr
Programming TCP Server in C
Server.c
0)
}
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) <
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) error("ERROR on accept");
bzero(buffer,256);
n = recv(newsockfd,buffer,255,0);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
n = send(newsockfd,"I got your message",18,0);
if (n < 0) error("ERROR writing to socket"); Accept System Call – accepts a connection
on a socket
close(newsockfd);
close(sockfd);
#include <sys/types.h>
#include <sys/socket.h>
return 0;
int accept( int sockfd,
const struct sockaddr * addr,
socklen_t addrlen);
Returns a non-negative descriptor on success
sockfd: descriptor that must refer to a socket
addr: filled with address of connecting entity
addrlen: length of addr
Programming UDP Client in C
•
The client code for a datagram socket client is the same as that for a
stream socket with the following differences.
– the socket system call has SOCK_DGRAM instead of SOCK_STREAM as its
second argument & IPPROTO_UDP instead of IPPROTO_TCP as its third
argument.
– there is no connect() system call
– instead of send() and recv(), the client uses sendto() and recvfrom()
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
len = sizeof(struct sockaddr_in);
while (1) {
/* write */
n = sendto(sock,“Got your message\n",17, 0,(struct sockaddr *)
&server, len);
f (n < 0) error("sendto");
/* read */
n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from, len);
if (n < 0) error("recvfrom");
}
Programming UDP Server in C
•
Server code with a datagram socket is similar to the stream socket
code with following differences.
– Servers using datagram sockets do not use the listen() or the accept() system
calls.
– After a socket has been bound to an address, the program calls recvfrom() to
read a message or sendto() to send a message.
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
len = sizeof(struct sockaddr_in);
while (1) {
/* read */
n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from, len);
if (n < 0) error("recvfrom");
/* write */
n = sendto(sock,"Got your message\n",17, 0,(struct sockaddr
*)&from, len);
f (n < 0) error("sendto");
}
Programming Client-Server in C
•
In case of Windows Everything in the code is same as described previously
except the following differences
– You have to tell your compiler to link in the Winsock library, usually
called wsock32.lib or winsock32.lib
– On Visual C++, this can be done through the Project menu, under
Settings.... Click the Link tab, and look for the box titled "Object/library
modules". Add "wsock32.lib" to that list.
– On Visual Studio .NET, add “wsock32.lib” under Project menu, Properties ->
Linker -> Input -> Additional Dependencies
#include <winsock.h>
…..
void main(int argc,char *argv[]){
WSADATA wsda; // if this doesn’t work
// WSAData wsda; // then try this
WSAStartup(0x0101,&wsda);
…..
WSACleanup();
closesocket(sockfd);
}
Programming Client-Server in Java
Programming TCP Client-Server in Java
•
•
•
All the classes related to sockets are in the java.net package, so make
sure to import that package when you program sockets.
All the input/output stream classes are in the java.io package, include
this also
How to open a socket?
– If you are programming a client, then you would create an object of
Socket class
– Machine name is the machine you are trying to open a connection to,
– PortNumber is the port (a number) on which the server you are trying to
connect to is running. select one that is greater than 1,023! Why??
Socket MyClient;
try {
MyClient = new Socket("Machine name",
PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
Programming TCP Client-Server in Java
•
If you are programming a server, then this is how you open a socket:
ServerSocket MyService;
try {
MyServerice = new
ServerSocket(PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
•
When implementing a server you also need to create a socket object from the
ServerSocket in order to listen for and accept connections from clients.
Socket clientSocket = null;
try {
clientSocket = MyService.accept();
}
catch (IOException e) {
System.out.println(e);
}
Programming TCP Client-Server in Java
•
How to create an input stream?
– On the client side, you can use the DataInputStream class to create an
input stream to receive response from the server:
DataInputStream input;
try {
input = new
DataInputStream(MyClient.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}
– The class DataInputStream allows you to read lines of text and Java
primitive data types in a portable way. It has methods such as read,
readChar, readInt, readDouble, and readLine,.
DataInputStream input;
– On the server side,
tryyou
{ can use DataInputStream to receive input from
input = new
the client:
DataInputStream(clientSocket.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}
Programming TCP Client-Server in Java
•
How to create an output stream?
– On the client side, you can create an output stream to send information
to the server socket using the class PrintStream or DataOutputStream
of java.io:
PrintStream output;
try {
output = new
PrintStream(MyClient.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
has
} methods for displaying textual representation
– The class PrintStream
of Java primitive data types. Its write and println methods are important.
Also, you may want to use the DataOutputStream:
DataOutputStream output;
try {
output = new
DataOutputStream(MyClient.getOutputStream());
}
catch (IOException e) {
write aSystem.out.println(e);
single Java primitive type to the output stream.
}
– Many of its methods
The method writeBytes is a useful one.
Programming TCP Client-Server in Java
•
On the server side
– you can use the class PrintStream to send information to the client.
PrintStream output;
try {
output = new
PrintStream(clientSocket.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
}
•
Note: You can use the class DataOutputStream as mentioned previously.
Programming TCP Client-Server in Java
•
How to close sockets?
– You should always close the output and input stream before you close
the socket.
– On the client side:
try {
output.close();
input.close();
MyClient.close();
}
catch (IOException e) {
System.out.println(e);
}
– On the server
try {
side:output.close();
input.close();
clientSocket.close();
MyService.close();
}
catch (IOException e) {
System.out.println(e);
}
Programming UDP Client-Server in Java
•
How to open a datagram socket?
– If you are programming a client, then you would create an object of
DatagramSocket class
try {
DatagramSocket socket = new
DatagramSocket();
}
catch (IOException e) {
System.out.println(e);
}
•
If you are programming a server, then this is how you open a socket:
DatagramSocket socket = null;
try {
socket = new DatagramSocket(4445);
}
catch (IOException e) {
System.out.println(e);
}
Programming UDP Client-Server in Java
•
How to send/receive on Datagram sockets?
– On the client side, you can use the DatagramPacket class
– To send data
byte[] buf = new byte[256];
InetAddress address =
InetAddress.getByName(args[0]);
DatagramPacket packet = new DatagramPacket(buf,
buf.length, address, 4445);
socket.send(packet);
– To receive data
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData());
System.out.println(“Received from server: " +
received);
Programming UDP Client-Server in Java
•
How to send/receive on Datagram sockets?
– On the Server side, you can use the DatagramPacket class
– To receive data
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf,
buf.length);
socket.receive(packet);
• To send data
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length,
address, port);
socket.send(packet);
socket.close();
• How to close a Datagram socket?
References
•
•
•
•
•
Man pages in Linux
Accesssible through following command
– man 2 <system_call_name>
– E.g. man 2 socket
“Unix network programming” by Richard Stevens
Beej’s guide to Network Programming
http://beej.us/guide/bgnet/
The Java Tutorial – Custom Networking
http://java.sun.com/docs/books/tutorial/networking/
Lecture notes of cs423 from Dr. Bob Cotter
http://www.sce.umkc.edu/~cotterr/cs423_fs05/cs423_fs05_lectures.html