package my_network_test.zuse;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class TCPClient {
private final Socket socket;
public TCPClient() throws IOException {
int port = 4444;
String host = "localhost";
socket=new Socket(host, port);
}
public void service(){
System.out.println("客户端启动...");
try {
BufferedReader brLocal=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8),true);
String socketMsg;
while((socketMsg=brLocal.readLine())!=null){
pw.println(socketMsg);
//if(socketMsg.equals("end")) break;
BufferedReader brSocket=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg=brSocket.readLine();
if(msg==null){
break;
}
System.out.println("来自服务器消息:"+msg);
}
}catch (IOException e){
e.printStackTrace();
}finally {
System.out.println("end...");
try{socket.close();}catch (IOException e){e.printStackTrace();}
}
}
public static void main(String[] args) throws IOException{
TCPClient tcpClient=new TCPClient();
tcpClient.service();
}
}
JAVA服务器/客户端编程之阻塞式客户端
于 2022-03-15 10:40:25 首次发布