两个简单的Client实例

本文介绍了一个使用Java实现的简单客户端程序,该程序通过Socket连接到指定的服务器(如Google),发送HTTP请求并接收响应。此外,还展示了如何利用NIO(非阻塞I/O)进行更高效的网络通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[code="java"]import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
private static final String ip = "www.google.com";
private static final int port = 80;

public void start() {
try {
Socket socket = new Socket(ip, port);
OutputStream out = socket.getOutputStream();
out.write(getString().getBytes());
socket.shutdownOutput();

InputStream input = socket.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = -1;
while ((len = input.read(buff)) != -1) {
buffer.write(buff, 0, len);
}
System.out.println(buffer.toString());
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

private String getString() {
StringBuffer buffer = new StringBuffer();
buffer.append("GET / HTTP/1.1\r\n");
buffer.append("Accept: */*\r\n");
buffer.append("Accept-Language: zh-cn\r\n");
buffer.append("Accept-Encoding: gzip, deflate\r\n");
buffer.append("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)\r\n");
buffer.append("Host: localhost\r\n");
buffer.append("Connection: Keep-Alive\r\n\r\n");
return buffer.toString();
}

public static void main(String[] args) {
new Client().start();
}
}
[/code]

[code="java"]/**
* Copyright: Copyright (c) 2007
* <br>
* Company: Digifun
* <br>
* Date: Jan 6, 2010
*/
package navy.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
* Description:<br>
*
* @author HuangShuzhen
* @version 0.1
*/
public class Client
{
private ByteBuffer buffer = ByteBuffer.allocate(1024);

private SocketChannel channel;

private Selector selector;

SocketAddress address;

private boolean isRun = true;

private void start (String host, int port)
{
try
{
channel = SocketChannel.open();
channel.configureBlocking(false);
address = new InetSocketAddress(host, port);
channel.connect(address);

selector = Selector.open();
channel.register(selector, SelectionKey.OP_CONNECT);

while (isRun)
{
if (selector.select() > 0)
{
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext())
{
SelectionKey key = it.next();
it.remove();
if (key.isConnectable())
{
System.out.println("conn");
channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
// 正在建立连接
if (channel.isConnectionPending())
{
// 完成连接
channel.finishConnect();
}
}
else if (key.isReadable())
{
System.out.println("--------------------------read-------------------");
read(key);
}
else if (key.isWritable())
{
System.out.println("write");
write(getHeader());

}
}
}
}
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}

private byte[] read (SelectionKey key)
{
try
{
int lenght = channel.read(buffer);
System.out.println(lenght);
if (lenght > 0)
{
byte[] data = new byte[lenght];
buffer.flip();
buffer.get(data);
System.out.println(new String(data));
buffer.compact();
buffer.clear();
}else if(lenght ==-1){
isRun = false;
}

}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}

private byte[] write (String content)
{
ByteBuffer src = ByteBuffer.wrap(content.getBytes());
try
{
channel.write(src);
channel.register(selector, SelectionKey.OP_READ);
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}

private String getHeader ()
{
StringBuffer buffer = new StringBuffer();
buffer.append("GET /navy/ HTTP/1.1\r\n");
buffer.append("Accept: */*\r\n");
buffer.append("Accept-Language: zh-cn\r\n");
buffer.append("Accept-Encoding: gzip, deflate\r\n");
buffer.append("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)\r\n");
buffer.append("Host: \r\n");
buffer.append("Connection: Keep-Alive\r\n\r\n");
return buffer.toString();
}

public static void main (String[] args)
{
Client client = new Client();
client.start("www.google.com", 80);
// while(true);
}

private static void print (ByteBuffer buffer)
{
System.out.println("-----------------------------");
System.out.println("position:" + buffer.position());
System.out.println("limit:" + buffer.limit());
System.out.println("capacity:" + buffer.capacity());
System.out.println("-----------------------------");
}
}
[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值