Socket编程入门2——阻塞通信(交互)

MyServer2.java //等待客户连接,接受Client信息,等待用户键盘输入,返还给客户端

package com.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer2 {
    public static void main(String[] args) {
        MyServer2 ms2 = new MyServer2();
    }
    public MyServer2(){
        try {
            ServerSocket ss = new ServerSocket(9999);
            System.out.println("Server监听"+ss.getLocalPort()+"端口中");
            Socket s = ss.accept();
            while(true){
                BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                String info = br.readLine();  //从客户端读取到信息
                System.out.println("client:"+info);
                if("bye".equals(info)){
                    s.close();
                    break;
                }
                //键盘输入消息,发送
                BufferedReader keyin =new BufferedReader(new InputStreamReader(System.in));
                PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
                pw.println(keyin.readLine());

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

MyClient2.java  //主动连接主机,发送信息给服务端,读取信息,判断是否关闭连接

package com.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MyClient2 {

    public static void main(String[] args) {
        MyClient2 mc2 = new MyClient2();
    }

    public MyClient2() {
        try {
            Socket s = new Socket("127.0.0.1", 9999);
            // 键盘输入消息
            while (true) {
                BufferedReader keyin = new BufferedReader(
                        new InputStreamReader(System.in));
                String keyinfo = keyin.readLine();
                PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
                pw.println(keyinfo);
                //从服务器读取信息
                BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                String info  =  br.readLine();
                System.out.println("server:"+info);
                //如果客户端 输入'bye'则断开
                if("bye".equals(keyinfo)){
                    s.close();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

posted @ 2010-10-15 12:08  【小洲】  阅读(325)  评论(0编辑  收藏  举报