TCP通信-客戶端給服務端發送數據 -聊天室版本4
案例:
實現Client重複向Server發送控制檯輸入的數據,當Server接受全部數據結束後給出響應信息(全部接受完畢!您已下線)
分析:方便代碼優化,可以提取公共的內容,作爲父類,將發送數據和接送數據功能細分化,這樣看的更加純粹明瞭
1.定義一個發送數據方法sendMessage(String message)有參數的,receiveMessage()方法有返回值,因爲接受到的數據需要
2.定義方法時注意返回值的判斷,是否傳參的問題。
3.構造方法把socket傳遞過去兩個處理流。
代碼實現:
ChatProtocol類
public class ChatProtocol {
private Socket socket;
private DataOutputStream dos;
private DataInputStream dis;
public ChatProtocol(Socket socket) throws IOException {
this.socket = socket;
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
}
public ChatProtocol() {
super();
}
//發送數據
public void sendMessage(String message) throws IOException{
//發送數據類型
dos.writeByte(1);
//發送數據長度
byte[] bys = message.getBytes();
dos.writeInt(bys.length);
//發送數據內容
dos.write(bys);
dos.flush();
}
//接受數據
public String receiveMessage() throws IOException{
//接收數據類型
byte type = dis.readByte();
//接收數據長度
int len = dis.readInt();
byte[] bys = new byte[len];
//接收數據內容
dis.read(bys);
return new String(bys);
}
}
Client類
public class Client extends ChatProtocol{
public Client() {
super();
// TODO Auto-generated constructor stub
}
public Client(Socket socket) throws IOException {
super(socket);
}
public static void main(String[] args) throws UnknownHostException, IOException {
//創建Socket對象
Socket socket = new Socket("localhost", 10087);
//獲取流對象併發送數據
Scanner sc = new Scanner(System.in);
Client client = new Client(socket);
while(true){
String data = sc.nextLine();
client.sendMessage(data);
//判斷
if("886".equals(data)){
break;
}
}
String message = client.receiveMessage();
System.out.println(message);
sc.close();
socket.close();
}
}
Server類
public class Server extends ChatProtocol {
public Server() {
super();
// TODO Auto-generated constructor stub
}
public Server(Socket socket) throws IOException {
super(socket);
}
public static void main(String[] args) throws IOException {
//創建ServerSocket
ServerSocket ss = new ServerSocket(10087);
//建立連接
Socket socket = ss.accept();
Server server = new Server(socket);
while(true){
//接收數據
String message = server.receiveMessage();
System.out.println(message);
//886意味着Client要下線
if("886".equals(message)){
System.out.println("此客戶端下線!");
break;
}
}
//給出響應數據
server.sendMessage("接收完畢!您已下線!");
}
}