Os 2

U
university of Gujrat, pakistanstudent à university of Gujrat, pakistan

sockets,types of socket,real life example,socket programming,client side,parent side,server side,client side,

Assignment No # 2
Group members:
Syed Hamid Raza-016
Muhammad Feezan-021
Zia Ul Hassan-027
Subject:
Operatingsystem
Submitted to:
Sir Hafiz Usman Zia
Topic: Sockets
The network concept of a socket refers to the connection of one host to another
through the combination of compatible IP Addresses and ports.
Sockets are the receiving endpoints of a connection and the attached connections
between the sockets linking two separate hosts called Threads.
 Used for communication in client server system.
 It is an interface of client server architecture.
 Sockets are the low level endpoint used for processing information across a
network.
 Defined as end point for communication.
 A socket is identified by IP address concatenated with port numbers.
 Client: Ask for information from server.
 Server: Response of client request.
 Used for establishing both server client connection.
 Specific services of server that implemented (ftp, http).
(Above services listen specific ports numbers that are reserved for these specific
services).
Socket Types
o Internet socket
o Unix socket
o X.25 Socket etc…..
Internet Socket
Internet Sockets characterized by IP address (4 bytes) and port number (2
bytes).
It’s Transport Layer Protocol.
Typesof internetsocket
1) Stream Socket
a) Connection oriented
b) Rely on TCP to provide two-way communication.
2) Datagram Socket
a) Connection is unreliable.
b) Rely on UDP.
User Datagram Protocol
1) Message oriented.
2) No connection is established.
3) Light weight.
4) Small packet size UDP header- 8 bytes.
5) No error detection.
6) Data can’t have retrieved.
7) Corrupted data may be discarded or lead to out of order.
Types:
Connection oriented(TCP):
Known as reliable network services because data arrive in proper
sequence. For connection-oriented communications, each end point must
be able to transmit so that it can communicate.
Connection less (UDP):
Connectionless sockets do not establish a connection over which
data is transferred. Instead, the server application specifies its name
where a client can send requests.
Multicastsocket:
Data can be sent to multiple recipients.
Telephone Analogy
A telephone call over a telephony network works as follows:
Both parties should have telephone.
Both are assigned their specific numbers.
Turn on a ringer to listen for a caller.
Caller lifts telephone and dials a number.
Telephone rings and the receiver of the call picks it.
Both parties talk and exchange data.
After conversation is done they hang up the phone.
Dissecting the Analogy
An endpoint (telephone) for communication is created on both sides.
An address is assigned to both networks.
One of them initiate the connection.
Other will wait for establishment of connection.
Once connection is established, data is exchanged.
After data is exchanged, endpoints are closed.
Real life Examples
Common networking protocol’s like HTTP, FTP rely on sockets
underneath to make connections.
WWW (web pages) and all the browsers like google chrome,
Mozilla Firefox, Internet explorer etc…
P2P network (LimeWire, BitComet)
Telephone call is just work on the principle of sockets.
Socket programming/process
Socket programming is a way of connecting two nodes on a network to
communicate with each other. One socket (node) listens on a particular port at
an IP, while other socket reaches out to the other to form a connection. Server
forms the listener socket while client reaches out to the server.
IN C++
Server Side
// Server side C/C++ program to demonstrate Socket programming
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from server";
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
valread = read( new_socket , buffer, 1024);
printf("%sn",buffer );
send(new_socket , hello , strlen(hello) , 0 );
printf("Hello message sentn");
return 0;
}
Client Side
// Client side C/C++ program to demonstrate Socket programming
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
struct sockaddr_in address;
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("n Socket creation error n");
return -1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf("nInvalid address/ Address not supported n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr,
sizeof(serv_addr)) < 0)
{
printf("nConnection Failed n");
return -1;
}
send(sock , hello , strlen(hello) , 0 );
printf("Hello message sentn");
valread = read( sock , buffer, 1024);
printf("%sn",buffer );
return 0;
}
In JAVA From Book
import java.net.*;
import java.io.*;
public class DateServer
{
public static void main(String[] args) {
try {
ServerSocket sock = new ServerSocket(6013);
/* now listen for connections */
while (true) {
Socket client = sock.accept();
PrintWriter pout = new
PrintWriter(client.getOutputStream(), true);
/* write the Date to the socket */
pout.println(new java.util.Date().toString());
/* close the socket and resume */
/* listening for connections */
client.close();
}
}
catch (IOException ioe) {
System.err.println(ioe);
}
From Google
Client Side
// A Java program for a Client
import java.net.*;
import java.io.*;
public class Client
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
// string to read message from input
String line = "";
// keep reading until "Over" is input
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
// close the connection
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Client client = new Client("127.0.0.1", 5000);
}
}
Server Side
// A Java program for a Server
import java.net.*;
import java.io.*;
public class Server
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server(5000);
}
}

Recommandé

Network Sockets par
Network SocketsNetwork Sockets
Network SocketsPeter R. Egli
7.7K vues28 diapositives
Socket Programming par
Socket ProgrammingSocket Programming
Socket Programmingelliando dias
2K vues20 diapositives
Ppt of socket par
Ppt of socketPpt of socket
Ppt of socketAmandeep Kaur
14.5K vues17 diapositives
Application Layer and Socket Programming par
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programmingelliando dias
3.9K vues52 diapositives
Socket programming par
Socket programmingSocket programming
Socket programmingharsh_bca06
6K vues11 diapositives
Socket System Calls par
Socket System CallsSocket System Calls
Socket System CallsAvinash Varma Kalidindi
31.1K vues22 diapositives

Contenu connexe

Tendances

Socket programming par
Socket programmingSocket programming
Socket programmingUjjwal Kumar
2.2K vues17 diapositives
Tcp sockets par
Tcp socketsTcp sockets
Tcp socketsbabak danyal
1.7K vues13 diapositives
Elementary TCP Sockets par
Elementary TCP SocketsElementary TCP Sockets
Elementary TCP SocketsSaksham Khurana
4.7K vues20 diapositives
Sockets par
SocketsSockets
SocketsIndrasena Reddy
4K vues30 diapositives
Socket programming par
Socket programmingSocket programming
Socket programmingAnurag Tomar
855 vues39 diapositives
Lecture10 par
Lecture10Lecture10
Lecture10vantinhkhuc
527 vues20 diapositives

Tendances(20)

Socket programming using C par Ajit Nayak
Socket programming using CSocket programming using C
Socket programming using C
Ajit Nayak1.7K vues
Advanced Sockets Programming par elliando dias
Advanced Sockets ProgrammingAdvanced Sockets Programming
Advanced Sockets Programming
elliando dias3.4K vues
Programming TCP/IP with Sockets par elliando dias
Programming TCP/IP with SocketsProgramming TCP/IP with Sockets
Programming TCP/IP with Sockets
elliando dias5.8K vues
Socket programming in C par Deepak Swain
Socket programming in CSocket programming in C
Socket programming in C
Deepak Swain1.1K vues
Java Socket Programming par Vipin Yadav
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
Vipin Yadav2.2K vues
Socket programming par MdEmonRana
Socket programmingSocket programming
Socket programming
MdEmonRana124 vues
Socket Programming Tutorial par Jignesh Patel
Socket Programming TutorialSocket Programming Tutorial
Socket Programming Tutorial
Jignesh Patel36.6K vues

Similaire à Os 2

Unit 8 Java par
Unit 8 JavaUnit 8 Java
Unit 8 Javaarnold 7490
1.5K vues31 diapositives
Sockets par
SocketsSockets
Socketssivindia
2.1K vues27 diapositives
Socket Programming - nitish nagar par
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagarNitish Nagar
661 vues27 diapositives
Md13 networking par
Md13 networkingMd13 networking
Md13 networkingRakesh Madugula
538 vues27 diapositives
Socket Programming it-slideshares.blogspot.com par
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.comphanleson
1.6K vues48 diapositives

Similaire à Os 2(20)

Sockets par sivindia
SocketsSockets
Sockets
sivindia2.1K vues
Socket Programming - nitish nagar par Nitish Nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
Nitish Nagar661 vues
Socket Programming it-slideshares.blogspot.com par phanleson
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
phanleson1.6K vues
Socket Programming par CEC Landran
Socket ProgrammingSocket Programming
Socket Programming
CEC Landran6.6K vues
Lan chat system par Wipro
Lan chat systemLan chat system
Lan chat system
Wipro20.7K vues
Sockets par babu4b4u
Sockets Sockets
Sockets
babu4b4u269 vues
Lab manual cn-2012-13 par Sasi Kala
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
Sasi Kala17.3K vues
Socket Programming par leminhvuong
Socket  ProgrammingSocket  Programming
Socket Programming
leminhvuong1.7K vues
Socket.io v.0.8.3 par Cleveroad
Socket.io v.0.8.3Socket.io v.0.8.3
Socket.io v.0.8.3
Cleveroad116 vues
Network programming in Java par Tushar B Kute
Network programming in JavaNetwork programming in Java
Network programming in Java
Tushar B Kute15.1K vues

Plus de university of Gujrat, pakistan

Change management par
Change management Change management
Change management university of Gujrat, pakistan
336 vues14 diapositives
Latest Trends in Digital Marketing par
Latest Trends in Digital MarketingLatest Trends in Digital Marketing
Latest Trends in Digital Marketinguniversity of Gujrat, pakistan
83 vues14 diapositives
Dark web (2) par
Dark web (2)Dark web (2)
Dark web (2)university of Gujrat, pakistan
118 vues16 diapositives
Code of ethics and professional conduct (1) par
Code of ethics and professional conduct (1)Code of ethics and professional conduct (1)
Code of ethics and professional conduct (1)university of Gujrat, pakistan
91 vues12 diapositives
Certification accreditation and licensure (1) par
Certification accreditation and licensure (1)Certification accreditation and licensure (1)
Certification accreditation and licensure (1)university of Gujrat, pakistan
91 vues15 diapositives
biggest technology trends par
biggest technology trendsbiggest technology trends
biggest technology trendsuniversity of Gujrat, pakistan
32 vues20 diapositives

Plus de university of Gujrat, pakistan(20)

Dernier

ChatGPT and AI for Web Developers par
ChatGPT and AI for Web DevelopersChatGPT and AI for Web Developers
ChatGPT and AI for Web DevelopersMaximiliano Firtman
174 vues82 diapositives
Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu... par
Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu...Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu...
Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu...NUS-ISS
32 vues54 diapositives
AMD: 4th Generation EPYC CXL Demo par
AMD: 4th Generation EPYC CXL DemoAMD: 4th Generation EPYC CXL Demo
AMD: 4th Generation EPYC CXL DemoCXL Forum
126 vues6 diapositives
"Quality Assurance: Achieving Excellence in startup without a Dedicated QA", ... par
"Quality Assurance: Achieving Excellence in startup without a Dedicated QA", ..."Quality Assurance: Achieving Excellence in startup without a Dedicated QA", ...
"Quality Assurance: Achieving Excellence in startup without a Dedicated QA", ...Fwdays
33 vues39 diapositives
Samsung: CMM-H Tiered Memory Solution with Built-in DRAM par
Samsung: CMM-H Tiered Memory Solution with Built-in DRAMSamsung: CMM-H Tiered Memory Solution with Built-in DRAM
Samsung: CMM-H Tiered Memory Solution with Built-in DRAMCXL Forum
105 vues7 diapositives
Tunable Laser (1).pptx par
Tunable Laser (1).pptxTunable Laser (1).pptx
Tunable Laser (1).pptxHajira Mahmood
21 vues37 diapositives

Dernier(20)

Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu... par NUS-ISS
Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu...Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu...
Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu...
NUS-ISS32 vues
AMD: 4th Generation EPYC CXL Demo par CXL Forum
AMD: 4th Generation EPYC CXL DemoAMD: 4th Generation EPYC CXL Demo
AMD: 4th Generation EPYC CXL Demo
CXL Forum126 vues
"Quality Assurance: Achieving Excellence in startup without a Dedicated QA", ... par Fwdays
"Quality Assurance: Achieving Excellence in startup without a Dedicated QA", ..."Quality Assurance: Achieving Excellence in startup without a Dedicated QA", ...
"Quality Assurance: Achieving Excellence in startup without a Dedicated QA", ...
Fwdays33 vues
Samsung: CMM-H Tiered Memory Solution with Built-in DRAM par CXL Forum
Samsung: CMM-H Tiered Memory Solution with Built-in DRAMSamsung: CMM-H Tiered Memory Solution with Built-in DRAM
Samsung: CMM-H Tiered Memory Solution with Built-in DRAM
CXL Forum105 vues
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen... par NUS-ISS
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...
NUS-ISS23 vues
"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi par Fwdays
"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi
"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi
Fwdays26 vues
TE Connectivity: Card Edge Interconnects par CXL Forum
TE Connectivity: Card Edge InterconnectsTE Connectivity: Card Edge Interconnects
TE Connectivity: Card Edge Interconnects
CXL Forum96 vues
MemVerge: Gismo (Global IO-free Shared Memory Objects) par CXL Forum
MemVerge: Gismo (Global IO-free Shared Memory Objects)MemVerge: Gismo (Global IO-free Shared Memory Objects)
MemVerge: Gismo (Global IO-free Shared Memory Objects)
CXL Forum112 vues
AI: mind, matter, meaning, metaphors, being, becoming, life values par Twain Liu 刘秋艳
AI: mind, matter, meaning, metaphors, being, becoming, life valuesAI: mind, matter, meaning, metaphors, being, becoming, life values
AI: mind, matter, meaning, metaphors, being, becoming, life values
"Ukrainian Mobile Banking Scaling in Practice. From 0 to 100 and beyond", Vad... par Fwdays
"Ukrainian Mobile Banking Scaling in Practice. From 0 to 100 and beyond", Vad..."Ukrainian Mobile Banking Scaling in Practice. From 0 to 100 and beyond", Vad...
"Ukrainian Mobile Banking Scaling in Practice. From 0 to 100 and beyond", Vad...
Fwdays40 vues
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV par Splunk
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV
Splunk86 vues
Spesifikasi Lengkap ASUS Vivobook Go 14 par Dot Semarang
Spesifikasi Lengkap ASUS Vivobook Go 14Spesifikasi Lengkap ASUS Vivobook Go 14
Spesifikasi Lengkap ASUS Vivobook Go 14
Dot Semarang35 vues
.conf Go 2023 - Data analysis as a routine par Splunk
.conf Go 2023 - Data analysis as a routine.conf Go 2023 - Data analysis as a routine
.conf Go 2023 - Data analysis as a routine
Splunk90 vues
Empathic Computing: Delivering the Potential of the Metaverse par Mark Billinghurst
Empathic Computing: Delivering  the Potential of the MetaverseEmpathic Computing: Delivering  the Potential of the Metaverse
Empathic Computing: Delivering the Potential of the Metaverse
Business Analyst Series 2023 - Week 3 Session 5 par DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10165 vues

Os 2

  • 1. Assignment No # 2 Group members: Syed Hamid Raza-016 Muhammad Feezan-021 Zia Ul Hassan-027 Subject: Operatingsystem Submitted to: Sir Hafiz Usman Zia
  • 2. Topic: Sockets The network concept of a socket refers to the connection of one host to another through the combination of compatible IP Addresses and ports. Sockets are the receiving endpoints of a connection and the attached connections between the sockets linking two separate hosts called Threads.  Used for communication in client server system.  It is an interface of client server architecture.  Sockets are the low level endpoint used for processing information across a network.  Defined as end point for communication.  A socket is identified by IP address concatenated with port numbers.  Client: Ask for information from server.  Server: Response of client request.  Used for establishing both server client connection.  Specific services of server that implemented (ftp, http). (Above services listen specific ports numbers that are reserved for these specific services).
  • 3. Socket Types o Internet socket o Unix socket o X.25 Socket etc….. Internet Socket Internet Sockets characterized by IP address (4 bytes) and port number (2 bytes). It’s Transport Layer Protocol. Typesof internetsocket 1) Stream Socket a) Connection oriented b) Rely on TCP to provide two-way communication. 2) Datagram Socket a) Connection is unreliable. b) Rely on UDP. User Datagram Protocol 1) Message oriented. 2) No connection is established. 3) Light weight. 4) Small packet size UDP header- 8 bytes. 5) No error detection. 6) Data can’t have retrieved. 7) Corrupted data may be discarded or lead to out of order.
  • 4. Types: Connection oriented(TCP): Known as reliable network services because data arrive in proper sequence. For connection-oriented communications, each end point must be able to transmit so that it can communicate. Connection less (UDP): Connectionless sockets do not establish a connection over which data is transferred. Instead, the server application specifies its name where a client can send requests. Multicastsocket: Data can be sent to multiple recipients. Telephone Analogy A telephone call over a telephony network works as follows: Both parties should have telephone. Both are assigned their specific numbers. Turn on a ringer to listen for a caller. Caller lifts telephone and dials a number. Telephone rings and the receiver of the call picks it. Both parties talk and exchange data. After conversation is done they hang up the phone. Dissecting the Analogy An endpoint (telephone) for communication is created on both sides. An address is assigned to both networks. One of them initiate the connection. Other will wait for establishment of connection. Once connection is established, data is exchanged. After data is exchanged, endpoints are closed.
  • 5. Real life Examples Common networking protocol’s like HTTP, FTP rely on sockets underneath to make connections. WWW (web pages) and all the browsers like google chrome, Mozilla Firefox, Internet explorer etc… P2P network (LimeWire, BitComet) Telephone call is just work on the principle of sockets. Socket programming/process Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket (node) listens on a particular port at an IP, while other socket reaches out to the other to form a connection. Server forms the listener socket while client reaches out to the server. IN C++ Server Side // Server side C/C++ program to demonstrate Socket programming #include <unistd.h> #include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #define PORT 8080 int main(int argc, char const *argv[]) { int server_fd, new_socket, valread; struct sockaddr_in address;
  • 6. int opt = 1; int addrlen = sizeof(address); char buffer[1024] = {0}; char *hello = "Hello from server"; // Creating socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Forcefully attaching socket to the port 8080 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons( PORT ); // Forcefully attaching socket to the port 8080 if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) { perror("bind failed"); exit(EXIT_FAILURE); } if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) { perror("accept"); exit(EXIT_FAILURE); } valread = read( new_socket , buffer, 1024); printf("%sn",buffer ); send(new_socket , hello , strlen(hello) , 0 ); printf("Hello message sentn"); return 0; }
  • 7. Client Side // Client side C/C++ program to demonstrate Socket programming #include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #define PORT 8080 int main(int argc, char const *argv[]) { struct sockaddr_in address; int sock = 0, valread; struct sockaddr_in serv_addr; char *hello = "Hello from client"; char buffer[1024] = {0}; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("n Socket creation error n"); return -1; } memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); // Convert IPv4 and IPv6 addresses from text to binary form if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) { printf("nInvalid address/ Address not supported n"); return -1; } if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("nConnection Failed n"); return -1; } send(sock , hello , strlen(hello) , 0 ); printf("Hello message sentn"); valread = read( sock , buffer, 1024); printf("%sn",buffer );
  • 8. return 0; } In JAVA From Book import java.net.*; import java.io.*; public class DateServer { public static void main(String[] args) { try { ServerSocket sock = new ServerSocket(6013); /* now listen for connections */ while (true) { Socket client = sock.accept(); PrintWriter pout = new PrintWriter(client.getOutputStream(), true); /* write the Date to the socket */ pout.println(new java.util.Date().toString()); /* close the socket and resume */ /* listening for connections */ client.close(); } } catch (IOException ioe) { System.err.println(ioe); } From Google Client Side // A Java program for a Client import java.net.*; import java.io.*; public class Client { // initialize socket and input output streams private Socket socket = null; private DataInputStream input = null; private DataOutputStream out = null; // constructor to put ip address and port
  • 9. public Client(String address, int port) { // establish a connection try { socket = new Socket(address, port); System.out.println("Connected"); // takes input from terminal input = new DataInputStream(System.in); // sends output to the socket out = new DataOutputStream(socket.getOutputStream()); } catch(UnknownHostException u) { System.out.println(u); } catch(IOException i) { System.out.println(i); } // string to read message from input String line = ""; // keep reading until "Over" is input while (!line.equals("Over")) { try { line = input.readLine(); out.writeUTF(line); } catch(IOException i) { System.out.println(i); } } // close the connection try { input.close(); out.close(); socket.close(); } catch(IOException i) { System.out.println(i);
  • 10. } } public static void main(String args[]) { Client client = new Client("127.0.0.1", 5000); } } Server Side // A Java program for a Server import java.net.*; import java.io.*; public class Server { //initialize socket and input stream private Socket socket = null; private ServerSocket server = null; private DataInputStream in = null; // constructor with port public Server(int port) { // starts server and waits for a connection try { server = new ServerSocket(port); System.out.println("Server started"); System.out.println("Waiting for a client ..."); socket = server.accept(); System.out.println("Client accepted"); // takes input from the client socket in = new DataInputStream( new BufferedInputStream(socket.getInputStream())); String line = ""; // reads message from client until "Over" is sent while (!line.equals("Over")) { try { line = in.readUTF(); System.out.println(line); } catch(IOException i) {
  • 11. System.out.println(i); } } System.out.println("Closing connection"); // close connection socket.close(); in.close(); } catch(IOException i) { System.out.println(i); } } public static void main(String args[]) { Server server = new Server(5000); } }