在java中面向连接的类有两种形式,它们分别是客户端和服务器端.客户端这一部分是最简单的,所以我们先讨论它.
列表9.1列出了一个简单的客户端的程序.它向一个服务器发出一个请求,取回一个html文档,并把它显示在控制台上.
9.1一个简单的socket客户端
import java.io.*;
import java.net.*;
/**
* 一个简单的从服务器取回一个html页面的程序
* 注意:merlin是本地机器的名字
*/
public class simplewebclient {
public static void main(string args[])
{
try
{
// 打开一个客户端socket连接
socket clientsocket1 = new socket("merlin", 80);
system.out.println("client1: " + clientsocket1);
// 取得一个网页
getpage(clientsocket1);
}
catch (unknownhostexception uhe)
{
system.out.println("unknownhostexception: " + uhe);
}
catch (ioexception ioe)
{
system.err.println("ioexception: " + ioe);
}
}
/**
*通过建立的连接请求一个页面,显示回应然后关闭socket
*/
public static void getpage(socket clientsocket)
{
try
{
// 需要输入和输出流
dataoutputstream outbound = new dataoutputstream(
clientsocket.getoutputstream() );
datainputstream inbound = new datainputstream(
clientsocket.getinputstream() );
// 向服务器发出http请求
outbound.writebytes("get / http/1.0 ");
// 读出回应
string responseline;
while ((responseline = inbound.readline()) != null)
{
// 把每一行显示出来
system.out.println(responseline);
if ( responseline.indexof("") != -1 )
break;
}
// 清除
outbound.close();
inbound.close();
clientsocket.close();
}
catch (ioexception ioe)
{
system.out.println("ioexception: " + ioe);
}
}
}
闽公网安备 35060202000074号