进阶day11-网络编程_TCP服务端实现
This commit is contained in:
@@ -35,6 +35,9 @@ public class TcpClientDemo04 {
|
|||||||
OutputStream os = client.getOutputStream();
|
OutputStream os = client.getOutputStream();
|
||||||
os.write("淘宝的官网".getBytes());
|
os.write("淘宝的官网".getBytes());
|
||||||
|
|
||||||
|
//注意:当发送完毕请求数据后,要设置结束的标记,否则服务器会长时间等待客户端的请求数据
|
||||||
|
client.shutdownOutput();
|
||||||
|
|
||||||
//3.获取字节输入流,接收响应数据
|
//3.获取字节输入流,接收响应数据
|
||||||
InputStream is = client.getInputStream();
|
InputStream is = client.getInputStream();
|
||||||
//一次读字节数组的方式来读取响应数据
|
//一次读字节数组的方式来读取响应数据
|
||||||
|
|||||||
61
javaSE-day11/src/com/inmind/tcp03/TcpServerDemo04.java
Normal file
61
javaSE-day11/src/com/inmind/tcp03/TcpServerDemo04.java
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package com.inmind.tcp03;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.net.ServerSocket;
|
||||||
|
import java.net.Socket;
|
||||||
|
|
||||||
|
/*
|
||||||
|
在java中使用一个类表示服务端ServerSocket
|
||||||
|
构造方法:
|
||||||
|
ServerSocket(int port) 创建绑定到指定端口的服务器套接字。
|
||||||
|
|
||||||
|
常用方法:
|
||||||
|
Socket accept() 侦听要连接到客户端请求并接受它。
|
||||||
|
void close() 关闭此套接字。
|
||||||
|
InetAddress getInetAddress() 返回套接字所连接的地址。
|
||||||
|
InputStream getInputStream() 返回此套接字的输入流.(接收请求数据的)
|
||||||
|
OutputStream getOutputStream() 返回此套接字的输出流。 (发送响应数据)
|
||||||
|
void shutdownOutput() 禁用此套接字的输出流 (设置了一个发送请求数据的结束标记)
|
||||||
|
void close() 关闭此套接字。
|
||||||
|
|
||||||
|
服务器实现步骤:
|
||||||
|
1.创建服务器对象
|
||||||
|
2.接收客户端请求
|
||||||
|
3.获取请求数据
|
||||||
|
4.业务逻辑代码
|
||||||
|
5.发送响应数据
|
||||||
|
6.释放资源
|
||||||
|
*/
|
||||||
|
public class TcpServerDemo04 {
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
//1.创建服务器对象
|
||||||
|
//ServerSocket(int port) 创建绑定到指定端口的服务器套接字。
|
||||||
|
ServerSocket server = new ServerSocket(10001);
|
||||||
|
System.out.println("服务启动了");
|
||||||
|
|
||||||
|
//2.接收客户端请求
|
||||||
|
//Socket accept() 侦听要连接到客户端请求并接受它。
|
||||||
|
Socket clientSocket = server.accept();//阻塞方法
|
||||||
|
|
||||||
|
//3.获取请求数据
|
||||||
|
InputStream is = clientSocket.getInputStream();
|
||||||
|
byte[] buf = new byte[1024];
|
||||||
|
int len;
|
||||||
|
while ((len = is.read(buf)) != -1) {
|
||||||
|
//打印获取的请求数据
|
||||||
|
System.out.println(new String(buf,0,len));
|
||||||
|
}
|
||||||
|
//4.业务逻辑代码
|
||||||
|
String result = "www.taobao.com";
|
||||||
|
|
||||||
|
//5.发送响应数据
|
||||||
|
OutputStream os = clientSocket.getOutputStream();
|
||||||
|
os.write(result.getBytes());
|
||||||
|
|
||||||
|
//6.释放资源
|
||||||
|
clientSocket.close();
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user