Network

General info

Return to top

Client Socket

Return to top

ServerSocket

Return to top

TCP/IP Example

Code provided by Sun's education.

//Server
import java.net.*;
import java.io.*;

public class SimpleServer {
    public static void main(String args[]) {
 	ServerSocket s = null;
 	Socket s1;
 	String sendString = "Hello Net World!";
 	int slength = sendString.length();
 	OutputStream s1out;
 	DataOutputStream dos;

 // Register your service on port 5432
 	try {
 	    s = new ServerSocket(5432);
 	} catch (IOException e) {
 // ignore
 	}
 // Run the listen/accept loop forever
	 while (true) {
 	    try {
 // Wait here and listen for a connection
 			s1=s.accept();

 // Get a communication stream associated with
 // the socket
 			s1out = s1.getOutputStream();
 			dos = new DataOutputStream (s1out);

 // Send your string!
 // (UTF provides machine independence)
 		dos.writeUTF(sendString);

 // Close the connection, but not the server socket
 		dos.close();
 		s1out.close();
 		s1.close();
 	     } catch (IOException e) {
 // ignore
             }
         }
     }
 }

//client
import java.net.*;
import java.io.*;

public class SimpleClient {

     public static void main(String args[]) throws IOException {
         int c;
         Socket s1;
         InputStream s1In;
         DataInputStream dis;

 // Open your connection to a server, at port 5432
 // localhost used here
         s1 = new Socket("127.0.0.1",5432);

 // Get an input file handle from the socket and
 // read the input
         s1In = s1.getInputStream();
         dis = new DataInputStream(s1In);

         String st = new String (dis.readUTF());
         System.out.println(st);

 // When done, just close the connection and exit
         dis.close();
         s1In.close();
         s1.close();
     }
 }

Return to top

UDP Sockets

Return to top

RMI

Return to top