Server客户端:
建立服务端监听socket,等待接收请求,通信之后,关闭socket
Client客户端:
创建Socket对象,指明连接的服务器的地址和端口号,连接建立后,通过输出流向服务器端发送请求信息,关闭socket
Server服务端代码:
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
public static void main(String[] args) throws Exception
{
// 创建服务端
ServerSocket server = new ServerSocket(6666);
// 服务端阻塞式监听客户端连接请求
// 接收到连接请求,则创建一个socket实例,与客户端通信
Socket client = server.accept();
// 获取InputStream读取数据
InputStream in = client.getInputStream();
byte[] b = new byte[1024];
// 客户端关闭输出流后服务端会读取到-1标志
while(-1 != in.read(b))
{
System.out.println(new String(b));
}
// 获取OutputStream输出数据
OutputStream out = client.getOutputStream();
out.write("hello, client".getBytes());
// 输出结束,关闭输出流
client.shutdownOutput();
System.out.println("Server close. " + System.currentTimeMillis());
server.close();
}
}
Client客户端代码:
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SocketClient {
public static void main(String[] args) throws Exception
{
// 请求连接服务端,握手成功,返回Socket实例
Socket client = new Socket("127.0.0.1",6666);
// 获取输入输出流,读写数据(与服务端数据读写操作相同)
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
out.write("hello, server".getBytes());
client.shutdownOutput();
byte[] b = new byte[1024];
while(-1 != in.read(b))
{
System.out.println(new String(b));
}
System.out.println("Client close. " + System.currentTimeMillis());
client.close();
}
}
BIO模式缺点:
每个请求都需要创建独立的线程,与对应的客户端进行通信。 连接建立后,如果当前线程暂时没有数据可读,则线程就阻塞在 Read 操作上,造成线程资源浪费