进阶day11-网络编程_TCP客户端实现
This commit is contained in:
50
javaSE-day11/src/com/inmind/tcp03/TcpClientDemo04.java
Normal file
50
javaSE-day11/src/com/inmind/tcp03/TcpClientDemo04.java
Normal file
@@ -0,0 +1,50 @@
|
||||
package com.inmind.tcp03;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.Socket;
|
||||
|
||||
/*
|
||||
TCP的客户端功能实现
|
||||
在java中使用一个类Socket表示客户端
|
||||
构造方法:
|
||||
Socket(String host, int port) 创建流套接字并将其连接到指定主机上的指定端口号。
|
||||
|
||||
常用方法:
|
||||
void close() 关闭此套接字。
|
||||
InetAddress getInetAddress() 返回套接字所连接的地址。
|
||||
InputStream getInputStream() 返回此套接字的输入流.(接收响应数据的)
|
||||
OutputStream getOutputStream() 返回此套接字的输出流。 (发送请求)
|
||||
void shutdownOutput() 禁用此套接字的输出流 (设置了一个发送请求数据的结束标记)
|
||||
|
||||
客户端的实现步骤:
|
||||
1.创建客户端对象
|
||||
2.获取字节输出流,发送请求数据
|
||||
3.获取字节输入流,接收响应数据
|
||||
4.释放资源
|
||||
|
||||
*/
|
||||
public class TcpClientDemo04 {
|
||||
public static void main(String[] args) throws IOException {
|
||||
//1.创建客户端对象
|
||||
//Socket(String host, int port) 创建流套接字并将其连接到指定主机上的指定端口号。
|
||||
Socket client = new Socket("192.168.22.51", 10001);
|
||||
|
||||
//2.获取字节输出流,发送请求数据
|
||||
OutputStream os = client.getOutputStream();
|
||||
os.write("淘宝的官网".getBytes());
|
||||
|
||||
//3.获取字节输入流,接收响应数据
|
||||
InputStream is = client.getInputStream();
|
||||
//一次读字节数组的方式来读取响应数据
|
||||
byte[] bytes = new byte[1024];
|
||||
int len;
|
||||
while ((len = is.read(bytes)) != -1) {
|
||||
//输出响应结果
|
||||
System.out.println(new String(bytes,0,len));
|
||||
}
|
||||
//4.释放资源
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user