码迷,mamicode.com
首页 > 编程语言 > 详细

java网络编程——socket实现简单的CS会话

时间:2020-03-07 12:55:09      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:异步   catch   false   imp   ignore   ace   end   lin   比较   

还记得当年学计网课时用python实现一个简单的CS会话功能,这也是学习socket网络编程的第一步,现改用java重新实现,以此记录。

  • 客户端
import java.io.*;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.Socket;

public class Client {
    public static void main(String[] args)throws IOException {
        Socket socket=new Socket();
//超时时间
        socket.setSoTimeout(3000);
        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(),2000),3000);

        System.out.println("已发起服务器连接");
        System.out.println("客户端信息:"+socket.getLocalSocketAddress()+"P:"+socket.getLocalPort());
        System.out.println("服务器信息:"+socket.getInetAddress()+"P:"+socket.getPort());

        try {
            todo(socket);
        }catch (Exception e){
            System.out.println("异常退出");
        }
    }
    private static void todo(Socket client)throws IOException{
        //构建键盘输入流
        InputStream in=System.in;
        BufferedReader input=new BufferedReader(new InputStreamReader(in));
        //得到socket输出流并转化为打印流
        OutputStream outputStream = client.getOutputStream();
        PrintStream socketPrintStream = new PrintStream(outputStream);
        //得到socket输入流并转化为BufferedReader
        InputStream inputStream = client.getInputStream();
        BufferedReader socketBufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        Boolean flag = true;
        do {
            //键盘读取一行
            String str = input.readLine();
            //发送到服务器
            socketPrintStream.println(str);
            //从服务器读取一行
            String echo = socketBufferedReader.readLine();
            if("bye".equalsIgnoreCase(echo)){//equalsIgnoreCase是忽略大小写的比较
                flag = false;
            }else{
                System.out.println(echo);
            }
        }while(flag);
        //资源释放
        socketBufferedReader.close();
        socketPrintStream.close();
    }
}
  • 服务器端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args)throws IOException{
        ServerSocket server = new ServerSocket(2000);

        System.out.println("服务器准备就绪");

        System.out.println("服务器信息:"+server.getLocalSocketAddress()+"P:"+server.getLocalPort());
        //等待客户端连接
        for (;;){
            Socket client = server.accept();//拿到客户端
            ClientHandle clientHandle = new ClientHandle(client);//客户端加入到一个异步线程
            clientHandle.start();//启动线程
        }

    }
    /**
    客户端消息处理
     */
    private static class ClientHandle extends Thread{
        private Socket socket;
        private Boolean flag = true;

        ClientHandle(Socket socket){
            this.socket=socket;
        }

        @Override
        public void run(){
            super.run();
            System.out.println("客户端连接:"+socket.getInetAddress()+"P:"+socket.getPort());

            try {

                //得到打印流,用于数据输出;服务器回送数据使用
                PrintStream socketOutput = new PrintStream(socket.getOutputStream());
                //得到输入流,用于接收数据
                BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                do{
                    //客户端拿到一条数据
                    String str = socketInput.readLine();
                    if("bye".equalsIgnoreCase(str)){
                        flag = false;
                        socketOutput.println("bye");
                    }else{
                        System.out.println(str);
                        socketOutput.println("回送:"+str.length());
                    }
                }while (flag);
            }catch (Exception e){
                System.out.println("异常断开");
            }finally {
                try {
                    socket.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            System.out.println("客户端已退出:"+socket.getInetAddress()+"P:"+socket.getPort());

        }
    }
}

java网络编程——socket实现简单的CS会话

标签:异步   catch   false   imp   ignore   ace   end   lin   比较   

原文地址:https://www.cnblogs.com/buptleida/p/12433531.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!