客户端Client源码如下:
public class Client {
public static void main(String[] args) throws Exception{
String readLine=null;
int port=4000;
byte ipAddressTemp[]={127,0,0,1};
InetAddress ipAddress = InetAddress.getByAddress(ipAddressTemp);
//1.初始化Socket
Socket socket=new Socket(ipAddress,port);
//创建三个流,系统输入流BufferedReader systemIn,socket输入流BufferedReader socketIn,socket输出流PrintWriter socketOut;
BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in));
BufferedReader socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter socketOut = new PrintWriter(socket.getOutputStream());
while (readLine!="bye"){
System.out.println("Client");
readLine=systemIn.readLine();
socketOut.println(readLine);
socketOut.flush(); //赶快刷新使Server收到,也可以换成socketOut.println(readline, ture)
String inTemp=socketIn.readLine();
System.out.println("Server: "+ inTemp);
}
systemIn.close();
socketIn.close();
socketOut.close();
socket.close();
}
}
服务器Server源码如下:
public class Server {
public static void main(String[] args) throws Exception {
String readLine=null;
int port=4000;
//1.初始化socket,绑定端口
ServerSocket serverSocket=new ServerSocket(port);
//2.调用服务器的accept()进行阻塞(程序会在这等待),当有申请连接时会打开阻塞并返回一个socket
Socket socket=serverSocket.accept();
BufferedReader systemIn= new BufferedReader(new InputStreamReader(System.in));
BufferedReader socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter socketOut=new PrintWriter(socket.getOutputStream());
while (readLine!="bye"){
String inTemp=socketIn.readLine();
System.out.println("Client: "+ inTemp);
System.out.println("Server");
readLine=systemIn.readLine();
socketOut.println(readLine);
socketOut.flush();//赶快刷新使Client收到,也可以换成socketOut.println(readline, ture)
}
systemIn.close();
socketIn.close();
socketOut.close();
socket.close();
serverSocket.close();
}
}