java网络编程(6)——实现一个服务器把小写转大写

  实现一个服务器,通过我们发送的文本数据,然后转回大写放回,实现一个服务端与客户端的交互,用over来作为结束标记,具体代码如下:

客户端:

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();
        
            
    }

}

服务端:

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就结束连接==。

posted @ 2015-08-02 10:32  SevenLin  阅读(633)  评论(0编辑  收藏  举报