作者:blue薾孋 | 来源:互联网 | 2023-07-17 18:03
客户端程序:importjava.io.*;importjava.net.Socket;publicclassTCPSocket{publicstaticvoidmain(St
客户端程序:
import java.io.*;
import java.net.Socket;
public class TCPSocket {public static void main(String[] args) throws IOException{//客户端socketSocket s=new Socket("127.0.0.1",8888);//设置输入缓冲区BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));//设置socket输出流 发送客户端数据PrintWriter out=new PrintWriter(s.getOutputStream());//设置socket输入流 读取服务器返回的数据BufferedReader ss=new BufferedReader(new InputStreamReader(s.getInputStream()));String line=null;//输入数据while((line=bufr.readLine())!=null){//esc 结束if("esc".equals(line))break;//发送out.println(line);out.flush();//接收String upperStr=ss.readLine();System.out.println(upperStr);}s.close();}
}
服务端程序:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;public class TCPSeverSocket {public static void main(String[] args) throws IOException{//服务端socketServerSocket s=new ServerSocket(8888);//获取客户端socketSocket ss=s.accept();//获取客户端的读取流BufferedReader bufin=new BufferedReader(new InputStreamReader(ss.getInputStream()));//获取客户端的输出流PrintWriter bufOut=new PrintWriter(ss.getOutputStream());String line=null;while((line=bufin.readLine())!=null){System.out.println(line);bufOut.println(line.toUpperCase());bufOut.flush();}ss.close();s.close();}
}
运行结果:
客户端:
服务端: