Connecting to a Server 

  • Connecting to a server is extremely easy with Java's built in socket classes for communicating via HTTP. You will recall from day two how we connected to a web server using the GET and POST methods of HTTP. Well in java, the process is exactly the same Specifically, you create a socket object which connects to a server somewhere on the web using syntax such as the following: 

  • Socket s = new Socket("url", portNumber); 

  • Thus, the following code would open a socket to www.extropia.com on port 80: 

  • Socket s = new Socket("www.extropia.com", 80); 

  • So what happens if your application cannot reach the server specified? Well, it is essential that you place your networking within a try block which catches several errors such as UnknownHostException, MalformedURLException, and IOException. 

Additional Resources:

Network Programming in Java 
Table of Contents
Getting Information from a Remote Site 


Graphics & Media Lab. >> Библиотека | Курсы | Графикон

Hosted by Graphics & Media Lab
http://graphics.cs.msu.su
lab_logo
mailto: Laboratory