基于 Java 简单实现 Socket 通信
客户端向服务器写入字符串 服务端只能接收单行 会跳过一行 是怎么回事
服务端代码
package socket;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class Server {
private ServerSocket serverSocket;
public Server() {
try {
System.out.println("正在启动服务器...");
serverSocket = new ServerSocket(8088);
System.out.println("服务器启动成功...");
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
try {
System.out.println("等待客户连接...");
Socket socket = serverSocket.accept();
System.out.println("一个客户已连接");
InputStream in = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.println("客户说:");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
//System.out.println("客户说:"+line);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.start();
}
}
客户端代码
package socket;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
/*
聊天室客户端
*/
public class Client {
private Socket socket;
public Client(){
try {
System.out.println("正在连接服务器....");
socket=new Socket("192.168.168.102",8088);
System.out.println("服务器连接成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
public void start(){
try {
OutputStream out=socket.getOutputStream();
OutputStreamWriter osw=new OutputStreamWriter(out, StandardCharsets.UTF_8);
BufferedWriter bw=new BufferedWriter(osw);
PrintWriter pw=new PrintWriter(bw,true);
Scanner scanner=new Scanner(System.in);
System.out.println("请输入:");
while (true){
pw.println(scanner.next());
if(scanner.next().equals("exit")){
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client=new Client();
client.start();
}
}
![img](