基于TCP协议的客户端

时间:2024-01-14 09:55:14

基于TCP协议的客户端 此客户端能用于下一篇博客的单线程服务器和多线程服务器

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);//创建一个客户对象并与服务器相连  端口是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();
        }
    }
}