服务端
public class Server {
public static void main(String[] args) throws IOException {
//本机9999端口接听,等待链接
ServerSocket serverSocket = new ServerSocket(9527);
//无客户端连接时处于阻塞状态
System.out.println("服务端等待监听。。。");
Socket socket = serverSocket.accept();
System.out.println("服务端" + serverSocket.getClass());
InputStream inputStream = socket.getInputStream();
byte[] b = new byte[1024];
int read = 0;
while ((read = inputStream.read(b) )!= -1){
System.out.println(new String(b,0,read));
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello client".getBytes());
//socket.shutdownOutput();
inputStream.close();
outputStream.close();
socket.close();
serverSocket.close();
}
}
客户端
public class CLient {
public static void main(String[] args) throws IOException {
InetAddress localHost = InetAddress.getLocalHost();
Socket socket = new Socket("127.0.0.1", 9527);
System.out.println("客户端" + socket.getClass());
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello server".getBytes());
//通知对方自己写完了,可以读取了,如果不加服务端和客户端会出现阻塞
socket.shutdownOutput();
//读
InputStream inputStream = socket.getInputStream();
byte[] b = new byte[1024];
int readLen = 0;
while ((readLen = inputStream.read(b)) != -1){
System.out.println(new String(b, 0, readLen));
}
/* inputStream.close();
outputStream.close();
socket.close();*/
System.out.println("客户端退出。。。");
}
}