package socket;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Copyright (C), 2018-2021, Mr.Lin
* Author: Mr.Lin
* Date: 2021/12/1 21:46
* FileName: SocketAPI01Client
* Description: 客户端
*/
public class SocketAPI01Client {
public static void main(String[] args) throws IOException {
//连接本机的端口,如果连接成功则返回socket对象
Socket socket = new Socket(InetAddress.getLocalHost(),6666);
System.out.println("返回socket="+socket);
//连接上后通过socket.getOutputStream()得到和socket 对象关联的输出流对象
OutputStream os = socket.getOutputStream();
os.write("hello.server".getBytes());
os.close();
socket.close();
System.out.println("客户端退出。。。。");
}
}
package socket;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Copyright (C), 2018-2021, Mr.Lin
* Author: Mr.Lin
* Date: 2021/12/1 21:38
* FileName: SocketAPI01Server
* Description:服务器端
*/
public class SocketAPI01Server {
public static void main(String[] args) throws IOException {
//在本机的6666端口监听,等待连接
//要求在本机没有其他服务占用6666端口
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("端口6666等待连接。。。");
//当客户端连接则返回socket对象
Socket socket = serverSocket.accept();
System.out.println("对象已连接。。。");
//通过 socket.getInputStream()读取客户端写入到 数据通道的数据
InputStream is = socket.getInputStream();
//IO读取
byte [] bytes=new byte[1024];
int readLen=0;
while ((readLen=is.read(bytes)) !=-1){
System.out.println(new String(bytes,0,readLen));
}
is.close();
socket.close();
serverSocket.close();
}
}