java網絡編程(6)——實現一個服務器把小寫轉大寫

  實現一個服務器,經過咱們發送的文本數據,而後轉回大寫放回,實現一個服務端與客戶端的交互,用over來做爲結束標記,具體代碼以下:java

客戶端:服務器

package com.seven.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class TranClient {
    
    public static void main(String[] args) throws Exception{
        Socket socket = new Socket("127.0.0.1",10001);
        
        //文本數據,用字符流,讀取鍵盤
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        //負責寫
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        //讀取返回數據
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        
        String line = null;
        
        while((line = reader.readLine())!=null){
            if("over".equals(line)){
                break;
            }
            writer.write(line);
            writer.newLine();
            writer.flush();
            
            System.out.println("server return :" + in.readLine());
        }
        
        reader.close();
        socket.close();
        
            
    }

}

服務端:socket

package com.seven.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TranServer {

    public static void main(String[] args) throws Exception {
        
        ServerSocket serverSocket = new ServerSocket(10001);
        
        Socket socket = serverSocket.accept();
        //讀取數據
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        //寫回數據
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        
        String line = null;
        
        while((line = reader.readLine())!=null){
            writer.write(line.toUpperCase());
            writer.newLine();
            writer.flush();
        }
        
        writer.close();
        socket.close();
        
    }
    
}

這樣子,就能夠實現小寫轉大寫,輸入over就結束鏈接==。tcp

相關文章
相關標籤/搜索