|
First things first, what is a socket? A socket is like a... Gateway... Between two programs. It can be through the internet, across a network, or just contacting other programs running on the same computer. For this tutorial you should be familiar with IO and Exceptions.
First me create our socket and have it connect to something.
| CODE | try { Socket s = new Socket("server.servegame.org",43594); //Socket(ip, port) } catch(Exception e) {System.err.println(e);}
|
That would open a socket to server.servegame.org on port 43594 NOTE: You have to throw/catch an exception! Now, if the connection is successfully made to the server, then it will continue on with what it was doing. If the connection can not be made, it will execute the catch block.
| CODE | try { Socket s = new Socket("server.servegame.org",43594); System.out.println("UP"); } catch(Exception e) {System.out.println("DOWN");}
|
Basically, that would attempt to connect to the server, if successfull it would print UP, if not, it would stop what its doing and go directly to the catch block printing DOWN.
Now lets write a Client/Server application that will send a message to the server.
| CODE | import java.io.*; import java.net.*;
public class Client { public static void main(String[] rr) { try { Socket s = new Socket("localhost",5000); PrintWriter pw = new PrintWriter(s.getOutputStream()); pw.println("TEST"); pw.flush(); } catch (Exception e) {System.err.println(e);} } }
|
| CODE | import java.io.*; import java.net.*;
public class Server { public static void main(String[] rr) { try { ServerSocket ss = new ServerSocket(5000); Socket s = ss.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); while(true) { System.out.println(br.readLine()); } } catch(Exception e) {System.err.println(e);}
} }
|
So, in order to read from a socket, we need to tie it to an InputStreamReader and use the getInputStream method to.. attach... it to the Socket. For writing we just need to use getOutputStream.
This post has been edited by Miamoto on Jun 15 2006, 03:13 AM
|