Network Programming 1
|
|
- Mavis Donna Hopkins
- 6 years ago
- Views:
Transcription
1 Network Programming 1
2 Network Programming Java and C++ can easily be used for network programming based in the client-server model. The client-server model is probably the most commonly used model for communicating between applications running on different computers. It is also frequently used for establishing communication links between different applications running on the same computer. 2
3 In the client-server model, you may think of a server as a constantly running program that monitors a port for other applications, called clients, wishing to communicate with the server through that port. The server and client roles apply only to individual communication links. That is, an application A can be a server with respect to application B s role as a client for one communication link. Yet, on a different communication link, application A could be a client to application B s role as a server. 3
4 All communication in client-server links takes place through ports. The port numbers 0 through 255 are reserved for standard network services such as TELNET, FTP, FINGER, TFTP, ECHO, etc. But numbers above 255 can be used for more specialized user-created services. 4
5 Telnet service is a common example of client-server model of communication. On the remote machine there is a constantly running program called telnetd (for telnet daemon) that monitors a designated port, port 23, for requests for telnet connections. When a client seeks such a connection, it runs a program called telnet that sends to the server machine a socket number, which is a combination of the IP address of the client machine together with the port number that the client will use for communicating with the server. When the server receives the client socket number, it acknowledges the request by sending back to the client its own socket number, meaning its IP address and the port on which it will communicate with the client. 5
6 Establishing Socket Connections with Existing Servers in Java Let s say that a client seeks to connect to a server on port 80. This port is usually monitored by the HTTPD servers (the HyperText Transmission Protocol Daemon program) on machines on which such servers are installed and running. In response to an appropriately formatted GET request received from a client on port 80, an HTTPD server can send back a web page whose URL is embedded in the request. 6
7 A client wishing to receive web pages from an HTTPD server that monitors port 80 constructs a socket by Socket t = new Socket( webaddress, 80 ); For example, if we wanted to download the raw ascii of the Purdue University web page, the following invocation in our client program would work: Socket socket = new Socket( " 80 ); The Socket object thus constructed talks to the server on server s port 80 and delivers to it the client s socket number, which consists of the IP address of the client and the port number being used for communicating with the server. The server acknowledges this request by sending back its own socket number, which would be the concatenation of the IP address of the server and the number of the port the server will use for the connection with the client. 7
8 The Socket constructor call is for establishing communication with a server using what s referred to as a reliable, connection-based stream protocol, as in TCP (for Transmission Control Protocol). By appropriate handshaking with the destination machine, TCP ensures that a packet sent over a network was actually received at the destination. If the data was not received, it is re-transmitted. TCP is used by higher-level utility protocols such as Telnet, FTP (for File Transfer Protocol), SMTP (Simple Mail Transfer Protocol), rlogin (for remote log in), etc. 8
9 One can also construct a socket object that would permit communication based on the less reliable but faster datagram protocol, as used in UDP (for User Datagram Protocol). UDP is used by Trivial File Transfer Protocol (TFTP), the Remote Call Procedure (RCP), etc. UDP is particularly suitable for those applications where missing packets can be tolerated, as for example in audio and video transmissions. 9
10 The socket constructor throws the UnknownHostException if it is not able to establish a connection with the server. 10
11 Once a client has established a socket link with the server, the data can be sent to the server and received back from the server on the link using essentially the same methods that are used for reading from files and writing into files on a local machine. 11
12 The Socket class has two methods, getinputstream() and getoutputstream(), that return InputStream and OutputStream objects. OutputStream out = socket.getoutputstream(); PrintStream ps = new PrintStream( os, true ); InputStream in = socket.getinputstream(); InputStreamReader in_reader = new InputStreamReader( in ); BufferedReader br = new BufferedReader( in_reader ); The Reader object in reader turns the bytes output by the InputStream object in into Unicode characters. By feeding these into the BufferedReader object br, we can invoke the efficient readline() method of BufferedReader to output one line of text at a time. 12
13 GET /HTTP/1.1\n\n < chars -----> 13
14 //ClientSocket.java import java.io.*; import java.net.*; class ClientSocket { public static void main( String[] args ) { try { char[] urlarr = new char[256]; String prefix = " String webaddress = args[0]; int i = 0; while ( i < prefix.length() ) { urlarr[ i ] = prefix.charat( i ); i++; while ( i < ( webaddress.length() + prefix.length() ) ) { urlarr[i] = webaddress.charat( i - prefix.length() ); i++; while ( i < 256 ) { urlarr[ i ] = ; i++; String urlstring = new String( urlarr ); Socket socket = new Socket( webaddress, 80 ); 14
15 OutputStream os = socket.getoutputstream(); PrintStream ps = new PrintStream( os, true ); InputStream in = socket.getinputstream(); InputStreamReader in_reader = new InputStreamReader( in ); BufferedReader b_reader = new BufferedReader( in_reader ); ps.print( "GET " + urlstring + " /HTTP/1.1\n\n" ); boolean more = true; while (more) { String str = b_reader.readline(); if (str == null) more = false; else System.out.println(str); catch( IOException e ) {System.out.println( "Error: " + e ); 15
16 When this program is executed by the call java ClientSocket 16
17 HTTP/ OK Date: Mon, 03 Jan :49:15 GMT Server: Apache/1.3.9 (Unix) Connection: close Content-Type: text/html <html> <head> <title>purdue University - West Lafayette, Indiana</title> <meta name= keywords content= Purdue University, Boilermakers, Boilers, Col <meta name= AUTHOR content= Rick DeLucio, Office of Publications, Purdue Un <meta name= ROBOTS content= ALL > <meta name= DESCRIPTION content= This is the official website of Purdue Uni <style type= text/css > <!--.roll { color: black; text-decoration: underline; text-transform: none; lettera.roll:hover { color: gray --> </style> <BASE HREF= > </head> <body bgcolor= white link= black vlink= # alink= #ce9c00 >
18 Server Sockets in Java ServerSocket server = new ServerSocket( int portnumber ); ServerSocket server = new ServerSocket( 5000 ); ServerSocket server = new ServerSocket( 5000, 10 ); 18
19 Socket socket = server.accept(); 19
20 public class ChatServer { public static Vector clientvec = new Vector(); public static void main( String[] args ) { try { ServerSocket server = new ServerSocket( 5000 ); //(A) //(B) for (;;) { Socket socket = server.accept(); System.out.print( "A new client checked in: " ); ClientHandler clh = new ClientHandler( socket ); clientvec.addelement( clh ); clh.start(); catch( Exception e ) { System.out.println( e ); //(C) //(D) //(E) //(F) 20
21 The ClientHandler class has to serve following purposes: 1. Its constructor must first establish the I/O streams and then, for convenience, the Reader and Writer objects for reading information sent by the client and writing information to the client. 2. It must print on the client s terminal a welcome message. 3. It must ask the client for a name that the client would want to use in the chat room for identifying himself/herself. It must pre-pend all the messages from a client with his or her name. 4. It must inform the client to type bye for signing off from the chat room. 5. Upon receiving a bye from a client, it must close the I/O streams associated with that client and also close the thread. When a client signs off, this information must be broadcast to all other clients. 6. When a client first signs in, it must print on the client s terminal all of the chat that has taken place up that point. 7. It must broadcast each client s message on the terminals of all the other clients. 21
22 PrintWriter out = new PrintWriter( sock.getoutputstream() ); InputStream in_stream = sock.getinputstream(); InputStreamReader in_reader = new InputStreamReader( in_stream ); BufferedReader buff_reader = new BufferedReader( in_reader ); 22
23 out.println( "\n\nwelcome to the chat room"); out.println( "Type \"bye\" in a new line to terminate session." out.print( "Please enter your first name: " ); String username = buff_reader.readline(); 23
24 // chatstore is a static data member of type Vector // for the ClientHandler class if ( chatstore.size()!= 0 ) { out.println( "Chat history:\n\n" ); for (int i = 0; i < chatstore.size(); i++ ) out.println( (String) chatstore.elementat( i ) ); 24
25 for ( int i = 0; i < ChatServer.clientVec.size(); i++ ) / { ClientHandler cl = (ClientHandler) ChatServer.clientVec.elementAt( i ) if ( this!= cl ) / { cl.out.println(); cl.out.println( strwithname ); / cl.out.print( cl.username + ": " ); / cl.out.flush(); 25
26 buffered_reader.close(); out.close(); sock.close(); 26
27 java ChatServer telnet RVL2.ecn.purdue.edu
28 //ChatServer.java import java.io.*; import java.net.*; import java.util.*; public class ChatServer { public static Vector clientvec = new Vector(); public static void main( String[] args ) { try { ServerSocket server = new ServerSocket( 5000 ); for (;;) { Socket socket = server.accept(); System.out.print( "A new client checked in: " ); ClientHandler clh = new ClientHandler( socket ); clientvec.addelement( clh ); clh.start(); catch( Exception e ) { System.out.println( e ); ///////// class ClientHandler extends Thread ///////// class ClientHandler extends Thread { private String username; 28
29 private Socket sock; private static Vector chatstore = new Vector(); private BufferedReader buff_reader = null; private PrintWriter out = null; public ClientHandler( Socket s ) { try { sock = s; // out = new PrintWriter( sock.getoutputstream(), true /*autoflush*/ ); out = new PrintWriter( sock.getoutputstream() ); InputStream in_stream = sock.getinputstream(); InputStreamReader in_reader = new InputStreamReader( in_stream ); buff_reader = new BufferedReader( in_reader ); // ask for user name out.println( "\n\nwelcome to Avi Kak s chatroom"); out.println(); out.println( "Type \"bye\" in a new line to terminate session." ); out.println(); out.print( "Please enter your first name: " ); out.flush(); username = buff_reader.readline(); out.print("\n\n"); out.flush(); System.out.print( username + "\n\n" ); // show to new client all the chat that has taken place so far if ( chatstore.size()!= 0 ) { out.println( "Chat history:\n\n" ); for (int i = 0; i < chatstore.size(); i++ ) 29
30 out.println( (String) chatstore.elementat( i ) ); out.print("\n\n"); out.flush(); catch( Exception e ) { public void run() { try { boolean done = false; while (!done ) { out.print( username + ": " ); out.flush(); String str = buff_reader.readline(); if ( str.equals( "bye" ) ) { str = username + " signed off"; done = true; String strwithname = username + ": " + str; chatstore.addelement( strwithname ); for ( int i = 0; i < ChatServer.clientVec.size(); i++ ) { ClientHandler cl = (ClientHandler) ChatServer.clientVec.elementAt( i ); if ( this!= cl ) { cl.out.println(); cl.out.println( strwithname ); cl.out.print( cl.username + ": " ); cl.out.flush(); 30
31 System.out.println( username + " signed off" + "\n\n" ); buff_reader.close(); out.close(); sock.close(); catch ( Exception e ) { 31
32 telnet
33 Establishing Socket Connections with Existing Servers in C++ C++ can be used in object-oriented style for network programming in a manner very similar to Java. 33
34 The Qt library offers several C++ classes with the same high-level functionality as the Java classes we have used so far for network programming. For example, the class QSocket, like the Java class java.net.socket, can be used to create a buffered TCP socket connection with a named server on a designated port. The Qt class QServerSocket can be used to create TCP server sockets, like the java.net.serversocket class. Other Qt class useful for network programming are: QDns for asynchronous DNS lookup; QNetworkProtocol to serve as a base class for implementing new network protocols; QFtp, derived from QNetworkProtocol, that implements the FTP protocol; 34
35 QUrlOperator for operating on hierarchical structures (like file systems) using URL s; etc. 35
36 QSocket* socket = new QSocket(); socket->connecttohost( qstr, 80 ); // asynchronous call 36
37 The function connecttohost, like many other network related functions in the Qt library, works asynchronously, meaning that it returns before the designated operation has been completed. Whether or not a connection was really made and the state of that connection can be checked by trapping the signals emitted by a QSocket object. It is the programmer s job to provide slots for processing these signals and for connecting the signals with their respective slots. 37
38 After connecttohost() is invoked, the signals emitted by a QSocket object are: void hostfound() void connected() void connectionclosed() // host lookup succeeded // connection successfully established // when the host closed the connection void delayedclosedfinished() // if you invoke close() to close // the connection and there is buffered // output data to be written, the socket // object goes into the QSocket::Closing // state and returns immediately from the // call to close(). The data will continue // to be output until done. At that time // this signal is emitted. void readyread() // means there is incoming data to be read; // this signal is issued only once each // time there is fresh incoming data to be // read. void byteswritten( int nbytes) // This signal is emitted when data // is actually written to the network. // The nbytes parameters says how many // bytes were written. void error( int ) // an error occurred 38
39 The state of a QSocket object can be queried by invoking the function state() on the object. A connection can be in one of the following states defined through an enumeration for QSocket: Idle HostLookup Connecting Connection Closing // if there is no connection // during DNS lookup // while a TCP connection is being establis // while there is operational connection // if client has invoked close() on a conne // but there is still data in the output bu 39
40 The program consists of three files: ClientSocket.h ClientSocket.cc Makefile 40
41 //ClientSocket.h #ifndef CLIENTSOCKET_H #define CLIENTSOCKET_H #include <qsocket.h> #include <string> class ClientSocket : public QSocket { Q_OBJECT string wwwname; QSocket* socket; public: ClientSocket( string wwwname ); string constructhttprequest(); void socketclosed(); ~ClientSocket(); public slots: void reportconnected(); void reporthostfound(); void getwebpage(); void socketconnectionclosed(); void reporterror( int ); ; #endif 41
42 //ClientSocket.cc #include "ClientSocket.h" #include <qapplication.h> #include <qsocket.h> #include <string> #include <iostream> using namespace std; ClientSocket::ClientSocket( string sitename ) : QSocket( 0, 0 ) { wwwname = sitename; socket = new QSocket( ); connect( socket, SIGNAL( connected() ), this, SLOT( reportconnected() ) ); connect( socket, SIGNAL( hostfound() ), this, SLOT( reporthostfound() ) ); connect( socket, SIGNAL( readyread() ), this, SLOT( getwebpage() ) ); connect( socket, SIGNAL( connectionclosed() ), this, SLOT( socketconnectionclosed() ) ); connect( socket, SIGNAL( error( int ) ), this, SLOT( reporterror( int ) ) ); QString qstr( wwwname.c_str() ); socket->connecttohost( qstr, 80 ); // asynchronous call 42
43 ClientSocket::~ClientSocket() { string ClientSocket::constructHttpRequest( ) { char urlarr[256]; string prefix = " int i = 0; while ( i < prefix.length() ) { urlarr[ i ] = prefix[ i ]; i++; while ( i < ( wwwname.length() + prefix.length() ) ) { urlarr[i] = wwwname[ i - prefix.length() ]; i++; while ( i < 256 ) { urlarr[ i ] = ; i++; urlarr[255] = 0; string urlstring( urlarr ); string httprequeststring = "GET " + urlstring + " /HTTP/1.1\n\n"; return httprequeststring; void ClientSocket::reportHostFound() { cout << "host found" << endl; 43
44 void ClientSocket::reportConnected() { cout << "connection established" << endl; string httprequest = constructhttprequest(); int len = httprequest.size(); socket->writeblock( httprequest.c_str(), len ); void ClientSocket::getWebPage() { cout << "socket ready to read" << endl; int howmanybytes = socket->bytesavailable(); cout << "bytes available: " << howmanybytes << endl; while ( socket->canreadline() ) cout << socket->readline(); void ClientSocket::socketConnectionClosed() { socket->close(); if ( socket->state() == QSocket::Closing ) { // delayed close connect( socket, SIGNAL( delayedclosefinished() ), this, SLOT( socketclosed() ) ); else { // The socket is really closed socketclosed(); void ClientSocket::reportError( int e ) { cout << "error report from connecttohost" << endl; cout << "error id: " << e; void ClientSocket::socketClosed() { 44
45 cout << "Connection closed" << endl; exit( 0 ); int main( int argc, char* argv[] ) { QApplication app( argc, argv ); ClientSocket* sock = new ClientSocket( argv[1] ); return app.exec(); 45
46 Server Sockets in C++ Qt ChatServer.h ChatServer.cc Makefile_ChatServer 46
47 //ChatServer.h #ifndef CHATSERVER_H #define CHATSERVER_H #include <qserversocket.h> #include <qsocket.h> #include <qtextstream.h> #include <qstring.h> #include <vector> using namespace std; class ChatServer; class ClientHandler : public QObject { Q_OBJECT QSocket* handlersocket; QString* chatname; ChatServer* chatserver; QTextStream* os; public: ClientHandler( QSocket* sock, ChatServer* cserver ); ClientHandler(); ClientHandler( const ClientHandler& cl ); ClientHandler& operator=( const ClientHandler& other ); ~ClientHandler(); private slots: void readfromclient(); void reporterror( int ); ; class ChatServer : public QServerSocket { Q_OBJECT public: 47
48 vector<clienthandler> clientvector; ChatServer( int port ); void newconnection( int socketfd ); ~ChatServer(); ; #endif 48
49 //ChatServer.cc #include "ChatServer.h" #include <qapplication.h> #include <iostream> using namespace std; ChatServer::ChatServer( int port ) : QServerSocket( port ) { cout << "Server monitoring port " << port << endl; if (!ok() ) { qwarning( "Failed to register the server port" ); exit( 1 ); // You must provide an override implementation for // this method. When a client requests a connection, // this method will be called automatically with the // socket argument set to the filedescriptor associated // with the socket. void ChatServer::newConnection( int socketfd ) { // QSocket* socket = new QSocket( this ); QSocket* socket = new QSocket(); socket->setsocket( socketfd ); ClientHandler* clh = new ClientHandler( socket, this ); cout << "A new client checked in on socket FD " << socketfd << endl; ChatServer::~ChatServer(){ 49
50 ClientHandler::ClientHandler() { // Copy constructor is needed since it is the copies of // the ClientHandler objects that will be stored in the // vector clientvector ClientHandler::ClientHandler( const ClientHandler& other ) : handlersocket( other.handlersocket ), chatname( other.chatname ), chatserver( other.chatserver ), os( other.os ) { ClientHandler& ClientHandler::operator=( const ClientHandler& other ) { if ( this == &other ) return *this; cout << "ClientHandler assignment op invoked" << endl; if ( handlersocket!= 0 ) delete handlersocket; handlersocket = other.handlersocket; if ( chatname!= 0 ) delete chatname; chatname = other.chatname; if ( os!= 0 ) delete os; os = other.os; chatserver = other.chatserver; 50
51 ClientHandler::ClientHandler( QSocket* socket, ChatServer* chatserver ) : chatname(0), chatserver( chatserver ), handlersocket( socket ) { os = new QTextStream( handlersocket ); (*os) << "Welcome to a chat room powered by C++\n"; (*os) << ">>>> Enter bye to exit <<<\n"; (*os) << "Enter chat name: "; connect( handlersocket, SIGNAL( readyread() ), this, SLOT( readfromclient() ) ); connect( handlersocket, SIGNAL( error( int ) ), this, SLOT( reporterror( int ) ) ); // The destructor definition intentionally does not invoke the delete // operator on any of the objects pointed to by the data members of a // ClientHandler. In this program, the most frequent invocation of the // destructor is caused by the push_back statement in the // readfromclient() function. The push_back invocation causes the the // vector to be moved to a different location in the memory. The memory // occupied by the ClientHandler objects in the vector is freed by // invoking the destructor. Deleting the memory occupied the socket and // other objects pointed to by the data members of the ClientHandler // objects would lead to disastrous results. ClientHandler::~ClientHandler(){ void ClientHandler::reportError( int e ) { cout << "error report from connecttohost" << endl; cout << "error id: " << e << endl; 51
52 void ClientHandler::readFromClient() { QSocket* sock = (QSocket*) sender(); while ( sock->canreadline() ) { QString qstr = sock->readline(); // This block is for the case when a new chatter has just signed // in and supplied his/her chat name. The block sets the // chatname of the ClientHandler object assigned to this new // user. Next it pushes the ClientHandler object for this new // user in the vector clientvector. Subsequently, The block // informs all other current chatters that this new user has // signed in. if ( chatname == 0 ) { chatname = new QString( qstr.stripwhitespace() ); chatserver->clientvector.push_back( *this ); // now we have all for ( int i=0; i<chatserver->clientvector.size(); i++ ) { if ( *chatserver->clientvector[i].chatname!= *chatname && chatserver->clientvector[i].handlersocket!= 0 ) { QString outgoing = "\nmessage from chat server: " + *chatname + " signed in "; *chatserver->clientvector[i].os << outgoing; // This block treats the case when a chatter wants to sign out // by typing "bye". It broadcasts a message to all the other // chatters that this chatter is signing off. This block than // closes the socket. Note that socket pointer is set to null // in both the ClientHandler object assigned to the exiting // chatter and its copy the vector clientvector. else if ( qstr.stripwhitespace() == "bye" ) { 52
53 for ( int i=0; i<chatserver->clientvector.size(); i++ ) { QString outgoing( "\nmessage from the chat server: " + *chatname + " signed off" ); if ( *chatserver->clientvector[i].chatname!= *chatname && chatserver->clientvector[i].handlersocket!= 0 ) { *chatserver->clientvector[i].os << outgoing; handlersocket->close(); // delete handlersocket; // close connection to client handlersocket = 0; for ( int i=0; i<chatserver->clientvector.size(); i++ ) { if ( *chatserver->clientvector[i].chatname == *chatname ) chatserver->clientvector[i].handlersocket = 0; // This is the normal case encountered during the course of a // chat. The string typed in by a chatter is broadcast to all // the other chatters. The string is pre-pended by the name of // the chatter who typed in the string. else { cout << *chatname << ": " << qstr << endl; qstr.truncate( qstr.length() - 2 ); for ( int i=0; i<chatserver->clientvector.size(); i++ ) { if ( *chatserver->clientvector[i].chatname!= *chatname && chatserver->clientvector[i].handlersocket!= 0 ) { QString outgoing = "\n" + *chatname + ": " + qstr; *chatserver->clientvector[i].os << outgoing; // A chatter s terminal always shows his/her own name at // beginning of a new line. This way, when a chatter types in // his/her own message, it is always on a line that starts with 53
54 // his/her own name. for ( int i=0; i<chatserver->clientvector.size(); i++ ) { if ( chatserver->clientvector[i].handlersocket!= 0 ) { QString outgoing = "\n" + *chatserver->clientvector[i].chatname + ": "; *chatserver->clientvector[i].os << outgoing; int main( int argc, char* argv[] ) { QApplication app( argc, argv ); ChatServer* server = new ChatServer( 5000 ); return app.exec(); 54
Network. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark
Network Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark jbb@ase.au.dk Outline Socket programming If we have the time: Remote method invocation (RMI) 2 Socket Programming Sockets
More informationCOMP 213. Advanced Object-oriented Programming. Lecture 20. Network Programming
COMP 213 Advanced Object-oriented Programming Lecture 20 Network Programming Network Programming A network consists of several computers connected so that data can be sent from one to another. Network
More informationJava Networking (sockets)
Java Networking (sockets) Rui Moreira Links: http://java.sun.com/docs/books/tutorial/networking/toc.html#sockets http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets_p.html Networking Computers
More informationMulti-threaded Web Server (Assignment 1) Georgios Georgiadis
Multi-threaded Web Server (Assignment 1) Georgios Georgiadis Overview Multi-threaded Web Server What to do and how to do it HTTP messages Processes and threads ComputerComm '09 2 Multi-threaded Web Server
More informationTCP Networking in Java. Some reminders
TCP Networking in Java Some reminders Protocol Synonymous of Etiquette a code of behavior that delineates expectations for social behavior according to contemporary conventional norms within a society,
More informationOutlines. Networking in Java. Internet hardware structure. Networking Diagram. IP Address. Networking in Java. Networking basics
G52APR Application programming Networking in Java Michael Li http://www.cs.nott.ac.uk/~jwl/g52apr Outlines Networking basics Network architecture IP address and port Server-client model TCP and UDP protocol
More informationNetwork Programming. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff
Network Programming by Vlad Costel Ungureanu for Learn Stuff Java Network Protocols 2 Java Network Protocols 3 Addresses Innet4Address (32-bit) 85.122.23.145 - numeric pentalog.com symbolic Innet6Address
More informationPieter van den Hombergh Richard van den Ham. March 17, 2018
: Network : Network, Object Pieter van den Hombergh Richard van den Ham Fontys Hogeschool voor Techniek en Logistiek March 17, 2018 /FHTenL : Network March 17, 2018 1/21 Topics, Object Some everyday life
More informationNetworking Basics. network communication.
JAVA NETWORKING API Networking Basics When you write Java programs that communicate over the network, you are programming at the application layer. Typically, you don't need to concern yourself with the
More informationDM550 / DM857 Introduction to Programming. Peter Schneider-Kamp
DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ IN & OUTPUT USING STREAMS 2 Streams streams are
More informationPrevious lecture: threads G51PRG: Introduction to Programming Second semester Lecture 12 URL
Previous lecture: threads G51PRG: Introduction to Programming Second semester Lecture 12 What is a thread Why use multiple threads Issues and problems involved Java threads Natasha Alechina School of Computer
More informationCS 355. Computer Networking. Wei Lu, Ph.D., P.Eng.
CS 355 Computer Networking Wei Lu, Ph.D., P.Eng. Chapter 2: Application Layer Overview: Principles of network applications? Introduction to Wireshark Web and HTTP FTP Electronic Mail: SMTP, POP3, IMAP
More informationSocket 101 Excerpt from Network Programming
Socket 101 Excerpt from Network Programming EDA095 Nätverksprogrammering Originals by Roger Henriksson Computer Science Lund University Java I/O Streams Stream (swe. Ström) - A stream is a sequential ordering
More informationInternet Technology 2/7/2013
Sample Client-Server Program Internet Technology 02r. Programming with Sockets Paul Krzyzanowski Rutgers University Spring 2013 To illustrate programming with TCP/IP sockets, we ll write a small client-server
More informationWeb Server Project. Tom Kelliher, CS points, due May 4, 2011
Web Server Project Tom Kelliher, CS 325 100 points, due May 4, 2011 Introduction (From Kurose & Ross, 4th ed.) In this project you will develop a Web server in two steps. In the end, you will have built
More informationCSCD 330 Network Programming Spring 2018
CSCD 330 Network Programming Spring 2018 Lecture 6 Application Layer Socket Programming in Java Reading for Java Client/Server see Relevant Links Some Material in these slides from J.F Kurose and K.W.
More informationChapter 4: Processes
Chapter 4: Processes Process Concept Process Scheduling Operations on Processes Cooperating Processes Interprocess Communication Communication in Client-Server Systems 4.1 Process Concept An operating
More informationCS September 2017
Machine vs. transport endpoints IP is a network layer protocol: packets address only the machine IP header identifies source IP address, destination IP address Distributed Systems 01r. Sockets Programming
More informationLecture 3: Socket Programming
Lecture 3: Socket Programming Prof. Shervin Shirmohammadi SITE, University of Ottawa Fall 2005 CEG4183/ELG4183 3-1 Sockets From a logical perspective, a Socket is a communication end point. It is not a
More informationAdvanced Java Programming. Networking
Advanced Java Programming Networking Eran Werner and Ohad Barzilay Tel-Aviv University Advanced Java Programming, Spring 2006 1 Overview of networking Advanced Java Programming, Spring 2006 2 TCP/IP protocol
More informationLecture 11.1 I/O Streams
21/04/2014 Ebtsam AbdelHakam 1 OBJECT ORIENTED PROGRAMMING Lecture 11.1 I/O Streams 21/04/2014 Ebtsam AbdelHakam 2 Outline I/O Basics Streams Reading characters and string 21/04/2014 Ebtsam AbdelHakam
More informationprotocols September 15,
Contents SCI 351 4 Protocols, WWW Internet applications WWW, document technology Lennart Herlaar Original slides by Piet van Oostrum September 15, 2003 SCI351-4 1 X SCI351-4 1 X Internet applications How
More informationDistributed Systems Recitation 2. Tamim Jabban
15-440 Distributed Systems Recitation 2 Tamim Jabban Agenda Communication via Sockets in Java (this enables you to complete PS1 and start P1 (goes out today!)) Multi-threading in Java Coding a full Client-Server
More informationCPSC 441 Tutorial TCP Server. Department of Computer Science University of Calgary
CPSC 441 Tutorial TCP Server Department of Computer Science University of Calgary TCP Socket Client Server Connection Request Server Listening on welcoming socket Client Socket Server Socket Data Simple
More informationDistributed Systems COMP 212. Lecture 8 Othon Michail
Distributed Systems COMP 212 Lecture 8 Othon Michail HTTP Protocol Hypertext Transfer Protocol Used to transmit resources on the WWW HTML files, image files, query results, Identified by Uniform Resource
More informationTCP connections. Fundamentals of Internet Connections Objectives. Connect to an Echo port. java.net.socket
Objectives TCP connections To understand programming of clients that connect to servers via TCP To understand the basics of programming of servers that accept TCP connections To practice programming of
More informationDistributed Systems Recitation 2. Tamim Jabban
15-440 Distributed Systems Recitation 2 Tamim Jabban Project 1 Involves creating a Distributed File System (DFS) Released yesterday When/If done with PS1, start reading the handout Today: Socket communication!
More informationNetworking and Security
Chapter 03 Networking and Security Mr. Nilesh Vishwasrao Patil Government Polytechnic Ahmednagar Socket Network socket is an endpoint of an interprocess communication flow across a computer network. Sockets
More informationTopic 10: Network Programming
Topic 10: Network Programming Client-Server Model Host and Port Socket Implementing Client Implementing Server Implementing Server for Multiple Clients Client-Server Model Clients Request a server to provide
More informationCS 351 Design of Large Programs Sockets Example
CS 351 Design of Large Programs Sockets Example Brooke Chenoweth University of New Mexico Spring 2019 Socket Socket(String host, int port) InputStream getinputstream() OutputStream getoutputstream() void
More informationChapter 2 Applications and
Chapter 2 Applications and Layered Architectures Sockets Socket API API (Application Programming Interface) Provides a standard set of functions that can be called by applications Berkeley UNIX Sockets
More informationByte and Character Streams. Reading and Writing Console input and output
Byte and Character Streams Reading and Writing Console input and output 1 I/O basics The io package supports Java s basic I/O (input/output) Java does provide strong, flexible support for I/O as it relates
More informationJava.net Package and Classes(Url, UrlConnection, HttpUrlConnection)
Java.net Package and Classes(Url, UrlConnection, HttpUrlConnection) Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in
More informationInterprocess Communication
Interprocess Communication Nicola Dragoni Embedded Systems Engineering DTU Informatics 4.2 Characteristics, Sockets, Client-Server Communication: UDP vs TCP 4.4 Group (Multicast) Communication The Characteristics
More informationJava Support for developing TCP Network Based Programs
Java Support for developing TCP Network Based Programs 1 How to Write a Network Based Program (In Java) As mentioned, we will use the TCP Transport Protocol. To communicate over TCP, a client program and
More informationCS 2113 Software Engineering
CS 2113 Software Engineering Java 6: File and Network IO https://github.com/cs2113f18/template-j-6-io.git Professor Tim Wood - The George Washington University Project 2 Zombies Basic GUI interactions
More informationUnit 9: Network Programming
Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Unit 9: Network Programming 1 1. Background 2. Accessing
More informationChapter 4: Processes. Process Concept. Process State
Chapter 4: Processes Process Concept Process Scheduling Operations on Processes Cooperating Processes Interprocess Communication Communication in Client-Server Systems 4.1 Process Concept An operating
More informationJava in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.
Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static
More informationJAVA Network API. 2 - Connection-Oriented vs. Connectionless Communication
JAVA Network API To be discussed 1 - java.net... 1 2 - Connection-Oriented vs. Connectionless Communication... 1 3 - Connectionless:... 1 4 - Networking Protocols... 2 5 - Sockets... 2 6 - Multicast Addressing...
More informationDistributed Programming - Sockets
Distributed Programming - Sockets Piet van Oostrum May 25, 2009 Concurrency In praktische situaties krijgen we concurrency door: Processen Threads Interrupts (alleen intern in het O.S.) Processen Onafhankelijke
More informationPIC 20A Streams and I/O
PIC 20A Streams and I/O Ernest Ryu UCLA Mathematics Last edited: December 7, 2017 Why streams? Often, you want to do I/O without paying attention to where you are reading from or writing to. You can read
More informationCS 351 Week Advanced UNIX Programming: Rochkind, Marc J. 1. To learn about System Interprocess Communication (IPC). 2. To learn about Sockets.
CS 351 Week 11 Reading: 1. Advanced UNIX Programming: Rochkind, Marc J. Objectives: 1. To learn about System Interprocess Communication (IPC). 2. To learn about Sockets. Concepts: 1. Interprocess Communication
More informationPrinciples of Software Construction. Introduction to networks and distributed systems School of Computer Science
Principles of Software Construction Introduction to networks and distributed systems Josh Bloch Charlie Garrod School of Computer Science 1 Administrivia Homework 5 Best Frameworks available tonight Or
More informationCS2141 Software Development using C/C++ C++ Basics
CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short
More informationIntroduction to Socket Programming
Introduction to Socket Programming (Advanced Computer Networks) By Priyank Shah NET ID : pss160530 A Simple Question What are Sockets? Sockets are communication points on the same or different computers
More informationCS 11 java track: lecture 6
CS 11 java track: lecture 6 This week: networking basics Sockets Vectors parsing strings what is networking? the network: world-wide web of interconnected computers "the internet" networking: programming
More informationDM550 Introduction to Programming part 2. Jan Baumbach.
DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net Map ADT: Specification 2 maps work like dictionaries in Python interface Map specifies standard
More informationIT101. File Input and Output
IT101 File Input and Output IO Streams A stream is a communication channel that a program has with the outside world. It is used to transfer data items in succession. An Input/Output (I/O) Stream represents
More informationI/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O
I/O 10-7-2013 I/O in Java I/O streams vs. Reader/Writer HW#3 due today Reading Assignment: Java tutorial on Basic I/O public class Swimmer implements Cloneable { public Date geteventdate() { return (Date)
More informationWeek 13 Lab - Exploring Connections & Remote Execution
Week 13 Lab - Exploring Connections & Remote Execution COSC244 & TELE202 1 Assessment This lab is worth 0.5%. The marks are awarded for completing the programming exercise and answering the questions.
More informationFile IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20
File IO Computer Science and Engineering College of Engineering The Ohio State University Lecture 20 I/O Package Overview Package java.io Core concept: streams Ordered sequences of data that have a source
More informationJava Socket Application. Distributed Systems IT332
Java Socket Application Distributed Systems IT332 Outline Socket Communication Socket packages in Java Multithreaded Server Socket Communication A distributed system based on the client server model consists
More informationSimple Java Input/Output
Simple Java Input/Output Prologue They say you can hold seven plus or minus two pieces of information in your mind. I can t remember how to open files in Java. I ve written chapters on it. I ve done it
More informationDarshan Institute of Engineering & Technology for Diploma Studies
Streams A stream is a sequence of data. In Java a stream is composed of bytes. In java, 3 streams are created for us automatically. 1. System.out : standard output stream 2. System.in : standard input
More informationWorld Scientific Research Journal (WSRJ) ISSN: The Implementation of Tcp Socket Programming based on Java
World Scientific Research Journal (WSRJ) ISSN: 2472-3703 www.wsr-j.org The Implementation of Tcp Socket Programming based on Java Deen Chen Computer Science Department, North China Electric Power University,
More informationCOMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015 Announcements Assignment 4 is posted and Due on 29 th of June at 11:30 pm. Course Evaluations due
More informationCSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2012
Web clients in Java CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2012 The World Wide Web History Main components: URLs, HTTP Protocol, HTML Web support in Java Overview Connecting
More informationJAVA - NETWORKING (SOCKET PROGRAMMING)
JAVA - NETWORKING (SOCKET PROGRAMMING) http://www.tutorialspoint.com/java/java_networking.htm Copyright tutorialspoint.com The term network programming refers to writing programs that execute across multiple
More informationCSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014
CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014 Name: This exam consists of 5 problems on the following 6 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet
More informationCSCD 330 Network Programming
CSCD 330 Network Programming Lecture 8 Client-Server Programming Threads Winter 2015 Reading: Chapter 2, Relevant Links Some Material in these slides from J.F Kurose and K.W. Ross All material copyright
More informationCSCD 330 Network Programming Spring 2018
CSCD 330 Network Programming Spring 2018 Lecture 7 Application Layer Socket Programming in Java Reading: Chapter 2, Java links Relevant Links page Some Material in these slides from J.F Kurose and K.W.
More informationGetting Started in Java. Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park
Getting Started in Java Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park Hello, World In HelloWorld.java public class HelloWorld { public static void main(string [] args) { System.out.println(
More informationLab 1 : Java Sockets
Lab 1 : Java Sockets 1. Goals In this lab you will work with a low-level mechanism for distributed communication. You will discover that Java sockets do not provide: - location transparency - naming transparency
More informationCSCD 330 Network Programming
CSCD 330 Network Programming Lecture 8 Client-Server Programming Threads Spring 2017 Reading: Chapter 2, Relevant Links - Threads Some Material in these slides from J.F Kurose and K.W. Ross All material
More informationCSCD 330 Network Programming Winter 2019
CSCD 330 Network Programming Winter 2019 Lecture 7 Application Layer Socket Programming in Java Reading: Chapter 2, Java links Relevant Links page Some Material in these slides from J.F Kurose and K.W.
More informationSockets and RMI. CS151 Chris Pollett Dec. 5, 2005.
Sockets and RMI CS151 Chris Pollett Dec. 5, 2005. Outline Echo Server with Multiple Clients Client pull/server push Remote Method Invocation Proxy Pattern Echo Server with Multiple Clients public class
More informationTommy Färnqvist, IDA, Linköping University
Lecture 4 Threads and Networking in Java TDDC32 Lecture notes in Design and Implementation of a Software Module in Java 23 January 2013 Tommy Färnqvist, IDA, Linköping University 4.1 Lecture Topics Contents
More informationSpecial error return Constructors do not have a return value What if method uses the full range of the return type?
23 Error Handling Exit program (System.exit()) usually a bad idea Output an error message does not help to recover from the error Special error return Constructors do not have a return value What if method
More informationAssignment 2 CISC 650 Computer Networks Fall 2016 Due Date: 10/9/ :59PM ET Total Points: 100
Nova Southeastern University College of Engineering and Computing Assignment 2 CISC 650 Computer Networks Fall 2016 Due Date: 10/9/2016 11:59PM ET Total Points: 100 Note: Please include your name and the
More informationCSC 4900 Computer Networks: P2P and Sockets
CSC 4900 Computer Networks: P2P and Sockets Professor Henry Carter Fall 2017 Recap SMTP is the language that mail servers use to exchange messages. SMTP is push-based... why? You can run SMTP from a telnet
More informationSchool of Informatics, University of Edinburgh
CS1Bh Lecture Note 16 Case Study: Client/Server In this case study we look at providing a slightly more realistic client/server application and explore some of the issues that arise in this context. Specifically
More informationCS 10: Problem solving via Object Oriented Programming. Client/Server
CS 10: Problem solving via Object Oriented Programming Client/Server Agenda 1. Sockets 2. Server 3. MulAthreaded server 4. Chat server 2 Sockets are a way for computers to communicate IP: 1.2.3.4 HTTP
More informationCSCD 330 Network Programming
CSCD 330 Network Programming Lecture 8 Client-Server Programming Threads Spring 2018 Reading: Chapter 2, Relevant Links - Threads Some Material in these slides from J.F Kurose and K.W. Ross All material
More informationCS193j, Stanford Handout #26. Files and Streams
CS193j, Stanford Handout #26 Summer, 2003 Manu Kumar Files and Streams File The File class represents a file or directory in the file system. It provides platform independent ways to test file attributes,
More informationJava A.1 TCP/IP TCP. TCP_RO.java import java.net.*; import java.io.*;
II A p.1 A Java C Java TCP/IP TCP/IP A.1 A.1.1 TCP TCP_RO.java public class TCP_RO { public static void main(string[] argv) { Socket readsocket = new Socket(argv[0], Integer.parseInt(argv[1])); InputStream
More informationInfo 408 Distributed Applications programming 2 nd semester of 2017/2018 Credits: 5 Lecturer: Dr. Antoun Yaacoub
Lebanese University Faculty of Science I Master 1 degree Computer Science Info 408 Distributed Applications programming 2 nd semester of 2017/2018 Credits: 5 Lecturer: Dr. Antoun Yaacoub Starting Network
More informationSocket programming. Complement for the programming assignment INFO-0010
Socket programming Complement for the programming assignment INFO-0010 Outline Socket definition Briefing on the Socket API A simple example in Java Multi-threading and Synchronization Example : HTTP protocol
More informationObject-Oriented Programming Design. Topic : Streams and Files
Electrical and Computer Engineering Object-Oriented Topic : Streams and Files Maj Joel Young Joel Young@afit.edu. 18-Sep-03 Maj Joel Young Java Input/Output Java implements input/output in terms of streams
More informationChapter 11. Application-Layer Elements Ports
Chapter 11 Application-Layer Elements 11.1 Ports........................... 93 11.2 Sockets.......................... 95 11.2.1 Socket Domains, Types and Protocols....... 95 11.2.2 Operations on Sockets................
More informationCS2 Advanced Programming in Java note 8
CS2 Advanced Programming in Java note 8 Java and the Internet One of the reasons Java is so popular is because of the exciting possibilities it offers for exploiting the power of the Internet. On the one
More informationCOMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output
COMP 213 Advanced Object-oriented Programming Lecture 19 Input/Output Input and Output A program that read no input and produced no output would be a very uninteresting and useless thing. Forms of input/output
More informationOBJECT ORIENTED PROGRAMMING
1 OBJECT ORIENTED PROGRAMMING Lecture 14 Networking Basics Outline 2 Networking Basics Socket IP Address DNS Client/Server Networking Class & Interface URL Demonstrating URL Networking 3 Java is practically
More informationI/O Streams. Object-oriented programming
I/O Streams Object-oriented programming Outline Concepts of Data Streams Streams and Files File class Text file Binary file (primitive data, object) Readings: GT, Ch. 12 I/O Streams 2 Data streams Ultimately,
More informationCOMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015
COMP-202: Foundations of Programming Lecture 22: File I/O Jackie Cheung, Winter 2015 Announcements Assignment 5 due Tue Mar 31 at 11:59pm Quiz 6 due Tue Apr 7 at 11:59pm 2 Review 1. What is a graph? How
More informationSockets: Network io HOM HVD. Sockets, Object Streams and Serialization. Sockets. Sockets: Network io HOM HVD
: Network : Network, bject ieter van den Hombergh ichard van den Ham Fontys Hogeschool voor echniek en Logistiek March 17, 2018 /FHenL : Network March 17, 2018 1/21 opics, bject Some everyday life sockets:
More informationJAVA SOCKET PROGRAMMING
JAVA SOCKET PROGRAMMING WHAT IS A SOCKET? Socket The combination of an IP address and a port number. (RFC 793 original TCP specification) The name of the Berkeley-derived application programming interfaces
More informationComputer Engineering II Solution to Exercise Sheet Chapter 4
Distributed Computing FS 2018 Prof. R. Wattenhofer Computer Engineering II Solution to Exercise Sheet Chapter 4 1 Quiz Questions a) A user provides his login credentials. The server then returns a cookie
More informationChapter 10. IO Streams
Chapter 10 IO Streams Java I/O The Basics Java I/O is based around the concept of a stream Ordered sequence of information (bytes) coming from a source, or going to a sink Simplest stream reads/writes
More informationLab 10: Sockets 12:00 PM, Apr 4, 2018
CS18 Integrated Introduction to Computer Science Fisler, Nelson Lab 10: Sockets 12:00 PM, Apr 4, 2018 Contents 1 The Client-Server Model 1 1.1 Constructing Java Sockets.................................
More informationThe Java I/O System. Binary I/O streams (ASCII, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)
The Java I/O System Binary I/O streams (ASCII, 8 bits) InputStream OutputStream The decorator design pattern Character I/O streams (Unicode, 16 bits) Reader Writer Comparing binary I/O to character I/O
More informationSOCKETLIB. Requirements
SOCKETLIB SocketLib is an event based, semi-asynchronous socket stream. It derives from standard C++ sockets, therefore, all extractors (>>) and inserters (
More informationSockets: Network io HOM DOS HVD HEE. Sockets, Object Streams and Serialization. Sockets. Sockets: Network io HOM DOS HVD HEE
: Network : Network ieter van den Hombergh hijs Dorssers ichard van den Ham Uwe van Heesch, bject Fontys Hogeschool voor echniek en Logistiek April 22, 2016 /FHenL : Network April 22, 2016 1/19 opics :
More informationData Communication EDA344, DIT420 Description of Lab 1 and Optional Programming HTTP Assignment
Data Communication EDA344, DIT420 Description of Lab 1 and Optional Programming HTTP Assignment Aras Atalar Prajith R G 24/01/2018 Overview Lab 1 (Compulsory): WIRESHARK lab General Description Programming
More information1.00 Lecture 30. Sending information to a Java program
1.00 Lecture 30 Input/Output Introduction to Streams Reading for next time: Big Java 15.5-15.7 Sending information to a Java program So far: use a GUI limited to specific interaction with user sometimes
More informationClient/Server Computing & Socket Programming
CPSC 852 Intering Client/Server Computing & Socket Programming Michele Weigle Department of Computer Science Clemson University mweigle@cs.clemson.edu http://www.cs.clemson.edu/~mweigle/courses/cpsc852
More information3. Remote Procedure Call
3. Remote Procedure Call Master II Software Engineering Imed Bouchrika Dept of Mathematics & Computer Science University of Souk-Ahras imed@imed.ws Imed Bouchrika. Distributed Objects, Uni of Souk-Ahras
More informationCS2307 NETWORKS LAB 1. Programs using TCP Sockets (like date and time server & client, echo server & client, etc.) 2. Programs using UDP Sockets
CS2307 NETWORKS LAB 1. Programs using TCP Sockets (like date and time server & client, echo server & client, etc.) 2. Programs using UDP Sockets (like simple DNS) 3. Programs using Raw sockets (like packet
More informationNetworking: IPv6, UDP and TCP. Network Programming in Java UDP and TCP
Networking: IPv6, UDP and TCP Network Programming in Java UDP and TCP SCOMRED, November 2018 Instituto Superior de Engenharia do Porto (ISEP) Departamento de Engenharia Informática(DEI) SWitCH Computing
More information09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.
CSE 143 Java Streams Reading: 19.1, Appendix A.2 GREAT IDEAS IN COMPUTER SCIENCE REPRESENTATION VS. RENDERING 4/28/2002 (c) University of Washington 09-1 4/28/2002 (c) University of Washington 09-2 Topics
More information