JavaSE series code 72: Client program for Socket communication

Visualization software components
Software components with visual representation
Receive and respond to user events
Non visual software components
Timer control is an example of a non visual component
The spell checker is a stand-alone component that can be integrated with any application

客户端程序代码如下:  
import java.net.*;
import java.io.*;
public class MyClient implements Runnable
{
  Socket clientSocket;
  boolean flag=true;                   //标记是否结束
  Thread ConnenThread;                 //用于向服务器端发送信息
  BufferedReader cin;
  DataOutputStream cout;
  public static void main(String[] args)
  {   new MyClient().ClientStart();  }
  public void ClientStart()
  {
    try
    {                              //连接服务器端,这里使用本机
      clientSocket=new Socket("localhost",8080);
      System.out.println("已建立连接!");
      while(flag)
      {                            //获取流对象
        InputStream is=clientSocket.getInputStream();
        cin=new BufferedReader(new InputStreamReader(is));
        OutputStream os=clientSocket.getOutputStream();
        cout=new DataOutputStream(os);
        ConnenThread=new Thread(this);
        ConnenThread.start();     //启动线程,向服务器端发送信息
        String aline;
        while((aline=cin.readLine())!=null)
        {                        //接收服务器端的数据
          System.out.println(aline);
          if(aline.equals("bye"))
          {
            flag=false;
            ConnenThread.interrupt();
            break;
          }
        }
        cout.close();
        os.close();
        cin.close();
        is.close();
        clientSocket.close();    //关闭Socket连接
        System.exit(0);	
      }
    }
    catch(Exception e)
    {  System.out.println(e);  }
  }
  public void run()
  {
    while(true)
    {
      try
      {                     //从键盘接收字符并向服务器端发送
        int ch;
        while((ch=System.in.read())!=-1)
        {
          cout.write((byte)ch);
          if(ch=='\n')
            cout.flush();    //将缓冲区内容向输出流发送
        }
      }
      catch(Exception e)
      { System.out.println(e);  }
    }
  }
}
Published 73 original articles · praised 189 · 10,000+ views

Guess you like

Origin blog.csdn.net/blog_programb/article/details/105569651