Socket编程入门1——阻塞通信状态

MyServer.java   // 服务器等待连接状态。开放一个端口9999,接受消息,相应消息。

package com.test;

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

public class MyServer {

    public static void main(String[] args) {
        MyServer myServer = new MyServer();
    }
    public MyServer(){
        try {
            //在客户端开放一个端口
            ServerSocket ss = new ServerSocket(9999);
            System.out.println("Server:");
            //接受外来的请求
            Socket s = ss.accept();
            //读取客户端信息
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String accept = br.readLine();
            System.out.println(accept);
            //向客户端相应信息
            PrintWriter pw = new PrintWriter(s.getOutputStream(),true);  //一定要自动刷新 autoFlush
            pw.println("hello I'm server.");
        //    Thread.sleep(20000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

MyClient.java  // 客户端主动连接,发送信息,再等待服务器相应。

package com.test;

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

public class MyClient {

    public static void main(String[] args) {
        MyClient mc = new MyClient();
    }
    public MyClient(){
        try {
            System.out.println("Client:");
            //主动去接连服务器
            Socket s = new Socket("127.0.0.1",9999);
            //获取服务器的通道,发送信息。
            PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
            pw.println("hello I'm client.");
            //接受服务器回应的信息
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String info = br.readLine();
            System.out.println(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

上图:

ServerSocket

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