客户机(单线程 和多线程都可以用 主要是看服务器是单线程的还是多线程的)

package serverAndClient;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
 
public class JabberClient
{
 
    public static void main(String[] args) throws IOException
    {
        new KeHuJi();
    }
}
 
class KeHuJi
{
    BufferedReader in = null;
    PrintWriter out = null;
    public  String name = null;
 
    class JieShou extends TimerTask
    {
        public void run()
        {
            String string = null;
            try
            {
                string = in.readLine();
                if (string != null)
                {
                    System.out.println(string);
                }
            } catch (Exception e)
            {
                // TODO: handle exception
            }
 
        }
    }
 
    public KeHuJi() throws IOException
    {
        InetAddress addr = InetAddress.getLocalHost();
        Socket socket = null;
        String ipString = null;
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入服务器的ip");
        ipString = scanner.next();
        socket = new Socket(ipString, 8089);//新建一个客户机对象
        System.out.println("请输入的你的名字");
        name = scanner.next();
        scanner.close();
        try
        {
            System.out.println("连接成功");
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
 
            Timer timer = new Timer();
            JieShou jieShou = new JieShou();
            timer.schedule(jieShou, 10, 200);//每隔200毫秒就要查看一次输入流中是否有新的数据 并且把内容输出到屏幕
            while (true)
            {
                Scanner in1 = new Scanner(System.in);
                out.println(name + ":  " + in1.next());
            }
 
        } catch (Exception e)
        {
 
        }
        finally
        {
            socket.close();
        }
 
    }
 
}

 

posted @ 2016-07-27 11:11  -梦里不知身是客  阅读(489)  评论(0编辑  收藏  举报