package myfistsocket;

/*一个作为Server*/

import java.io.*;
import java.net.*;

class MynewServer
{
    publicstaticvoid main(String[] args) throws IOException
    {
        ServerSocket s = new ServerSocket(6666);
        System.out.println("服务器端------监听中.....");
        Socket socket = s.accept();

        System.out.println("开始:" + socket);

        GetMessage gm = new GetMessage(socket);
        SendMessage sm = new SendMessage(socket);

        Thread gt = new Thread(gm);
        Thread st = new Thread(sm);

        gt.start();
        st.start();
    }
}

// 接收消息
class GetMessage implements Runnable
{
    BufferedReader in;

    public GetMessage(Socket socket)
    {
        try
        {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }
        catch (IOException e)
        {

            e.printStackTrace();
        }
    }

    publicvoid run()
    {

        String str = "";

            while (true)
            {
                try
                {
                    str = in.readLine();
                }
                catch (IOException e)
                {

                    e.printStackTrace();
                }
                if (str.equals("q"))
                {
                    break;
                }

                System.out.print("客户端回应说:" + str);
            }
    }

}

// 发送消息
class SendMessage implements Runnable
{
    PrintWriter out;
    BufferedReader is;

    public SendMessage(Socket socket) throws IOException
    {

        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
        is = new BufferedReader(new InputStreamReader(System.in));
    }

    publicvoid run()
    {

        String input = new String();


            while (true)
            {
                try
                {
                    input = is.readLine().trim();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }

                out.println(input);
                System.out.print("服务器说:");
                out.flush();
            }

    }

}