有两个程序:客户端(Client)、服务端(Server)
客户端:
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
Socket socket;
public static void main(String[] args) throws IOException {
Client client = new Client(InetAddress.getLocalHost(), Server.port);
client.sendMes();
}
public Client(String ip, int port) throws IOException {
this.socket = new Socket(ip, port);
}
public Client(InetAddress ip, int port) throws IOException {
this.socket = new Socket(ip, port);
}
public void sendMes() throws IOException {
OutputStream os = socket.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write("hello");
bw.newLine();
bw.write("123");
bw.newLine();
bw.flush();
bw.close();
System.out.println("发送成功!");
}
/**
* 接受服务端返回的消息
* @throws IOException
*/
public void receiveMes() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(br.readLine());
}
}
服务端:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
ServerSocket serverSocket;
Socket socket;
static int port = 9999;
public static void main(String[] args) throws IOException {
Server server = new Server(port);
server.start1();
server.respond();
}
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
}
/**
* 服务端接受数据
* 步骤:
* 1. 创建 socket,用于接收数据
* 2. 用 socket.getInputStream() 接受通道里的数据
* 3. 用 BufferRead 读取,并显示
*
* @throws IOException
*/
public void start1() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ( !((line = br.readLine()).equals("\n")) ) {
System.out.println(line);
}
// System.out.println(br.readLine());
socket.shutdownInput();
System.out.println("服务端接收成功");
}
/**
* 服务端回应客户端
* @throws IOException
*/
public void respond() throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("nihao");
bw.newLine();
bw.flush();
bw.close();
}
public void close() throws IOException {
socket.close();
serverSocket.close();
}
}
Client里面的newLine()并不是表示流的结束,因此当没有close()时,在Server里 循环readLine()是不能结束循环的,一直在等待Client的继续传输,程序一直卡住。
而当加入close()时,Server可以顺利读取Client传输的数据,但是此时,Client的socket也随着流的关闭而关闭了,导致Server响应Client的数据就无法传输给Client。
PS:所有的读取,只要流没结束 就不会停下来。如果没有了 ,那就会等待,如果有,那就直接读。
版权声明:本文为GFreasy原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。