110 likes | 354 Views
Network Programming. CS3250. Core Java , Vol. II, Chapter 3. Book examples are available from http://horstmann.com/corejava. html
E N D
Network Programming CS3250
Core Java, Vol. II, Chapter 3. Book examples are available from http://horstmann.com/corejava.html • Web site for Practical TCP/IP Sockets in Java by Kenneth L. Calvert and Michael J. Donahoo. Slides and sample code: http://cs.ecs.baylor.edu/~donahoo/practical/JavaSockets/ • The Java Tutorial: http://java.sun.com/docs/books/tutorial/networking/index.html References
Server This socket is only used to get new connections to clients. The server does not read from or write to this socket. The server starts running first and waits for clients to connect. ServerSockets = new ServerSocket(8189); Socket incoming = s.accept(); Port number The Server from EchoServer.java, Core Java Vol. II, Ch. 3, pp. 178-179 (8th ed.)
Server Each time a client connects, the server gets a new socket which it uses only to communicate with that client. The server starts running first and waits for clients to connect. ServerSockets = new ServerSocket(8189); Socket incoming = s.accept(); Client programs do not use the ServerSocket class or call accept. Accepting Connections from EchoServer.java, Core Java Vol. II, Ch. 3, pp. 178-179 (8th ed.)
Client Server All transactions are initiated by clients. The client must know the name (or IP address) and port number of the server. Socket s = new Socket("localhost", 8189); The Client
Client Server The client gets the input and output streams from the socket to receive and send to the server. Socket s = new Socket("localhost", 8189); OutputStreamoutStream = s.getOutputStream(); PrintWriter out = new PrinterWriter (outStream, true); InputStreaminStream = s.getInputStream(); Scanner in = new Scanner(inStream); Input and Output Streams
Client Server Request The client uses the output stream to send a request to the server. out.println("connectGimli"); Sending to the Server
Client Server Reply The client uses the input stream to receive replies from the server. String reply = in.nextLine(); The nextLine method will block until the server sends a reply. If the program only has one thread, the whole program will be blocked, which is usually not good. Receiving a Reply
Client Messages from the server Server Thread 1 Messages to the server Thread 2 User I/O Using Threads