服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java socket编程(三)


  服务器sockets

列表9.2是一个服务器应用程序的一部分.

列表9.2 一个简单的服务器程序

/**
* 一个监听端口并提供html文档的程序.
*/
class simplewebserver {
public static void main(string args[])
{
serversocket serversocket = null;
socket clientsocket = null;
int connects = 0;
try
{
{
// 建立一个服务器socket
serversocket = new serversocket(80, 5);
while (connects < 5)
{
// 等待连接
clientsocket = serversocket.accept();
//服务连接
serviceclient(clientsocket);
connects++;
}
serversocket.close();
}
catch (ioexception ioe)
{
system.out.println("error in simplewebserver: " + ioe);
}
}
public static void serviceclient(socket client)
throws ioexception
{
datainputstream inbound = null;
dataoutputstream outbound = null;
try
{
// 得到io流
inbound = new datainputstream( client.getinputstream());
outbound = new dataoutputstream( client.getoutputstream());
//格式化输出(回应头和很少的html文档)
stringbuffer buffer = prepareoutput();
string inputline;
while ((inputline = inbound.readline()) != null)
{
//如果到了http请求的尾部,就发送回应
if ( inputline.equals("") )
{
outbound.writebytes(buffer.tostring());
break;
}
}
}
finally
{
// 清除
system.out.println("cleaning up connection: " + client);
tln("cleaning up connection: " + client);
outbound.close();
inbound.close();
client.close();
client.close();
}
}

扫描关注微信公众号