Professional Documents
Culture Documents
Tutorial Java
Tutorial Java
Application
TCP IP
UDP
TCP: Establish connection Maintain connection during the communication Release connection Reliable (Acknowledged, in order) UDP: No need to setup a link Independent packets Not reliable (no acknowledgement)
Device Drivers
Client-Server Architecture
request client response Host: www.vcu.edu Port: 80 Process request
Socket in Java
Two important classes
Socket: a normal socket as communication end ServerSocket: accept the incoming request
ServerSocket is an analogy to the custom service phone number, it will dispatch your call to a specialized staff--- normal Socket.
port numbers between 0 and 1,023 are reserved for for standard services, such as email, FTP, and HTTP. for your server, select one that is greater than 1,023
A simple client
smtpSocket = new Socket("128.172.167.167", 9998); os = new DataOutputStream(smtpSocket.getOu tputStream()); is = new DataInputStream(smtpSocket.getInpu tStream()); while (true){ inL=d.readLine(); os.writeBytes(inL+"\n"); if (inL.compareTo("quit")==0) break; // keep on reading from/to the socket till we receive the "Ok" from SMTP, // once we received that then we want to break. responseLine = is.readLine(); System.out.println("Server: " + responseLine); responseLine = is.readLine(); System.out.println("Server: " + responseLine); responseLine = is.readLine(); System.out.println("Server: " + responseLine); }
Reference
Class ServerSocke
A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester. accept() Listens for a connection to be made to this socket and accepts it. getInetAddress()
Returns the local address of this server socket.
Class Socket
This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines. Socket(InetAddress address, int port) connect(SocketAddress endpoint) Connects this socket to the server. getPort() Returns the remote port to which this socket is connected. getLocalPort() Returns the local port to which this socket is bound. getInputStream() Returns an input stream for this socket. getOutputStream() Returns an output stream for this socket. getInetAddress() Returns the address to which the socket is connected. getLocalAddress() Gets the local address to which the socket is bound.
Status check