====================客户端=========================
/*
* 客户端与服务端互动
* 说明:
* 1.使用的BufferedReader的readLine()方法要加上\r\n才能把数据输入;
* 2. 使用字符流一定要使用flush()才能把数据写出;
*/
package com.lin.michael;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException{
//1.建立客户端TCP服务,指定与此通信的服务器的IP和port
Socket socket = new Socket(InetAddress.getLocalHost(), 9090);
//2.获取Socket对象的输出流,并且使用转换流转化成字符输出流
OutputStreamWriter socketOut = new OutputStreamWriter(socket.getOutputStream());
//3. 从键盘的输入流读取数据
BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));
//从服务端读取回送数据,获取Socket的输入流对象
BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//4.写出数据
String line = null;
while((line=keyReader.readLine())!=null){
socketOut.write(line+"\r\n");
socketOut.flush();
System.out.println("服务端回送的数据是:" + socketReader.readLine());
}
//5.关闭资源
socket.close();
}
}
=====================服务端===============================
package com.lin.michael;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException{
//1.创建服务端tcp服务,坚挺端口
ServerSocket serverSocket = new ServerSocket(9090);
//2.接受服务端的连接并产生一个socket
Socket socket = serverSocket.accept();
//3.获取socket的输入流对象,并转换成字符输入流
BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//获取socket的输出流对象
OutputStreamWriter socketOut = new OutputStreamWriter(socket.getOutputStream());
//读取从键盘输入
BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));
//4.读取客户端的数据
String line = null;
while((line=socketReader.readLine())!=null){
System.out.println("服务端接收到的资源:" + line);
System.out.println("输入个客户端的数据:");
socketOut.write(keyReader.readLine()+"\r\n");
socketOut.flush();
}
serverSocket.close();
}
}