e11_1c.java

来自「java 初学者学习实例」· Java 代码 · 共 79 行

JAVA
79
字号
 import java.awt.*;
 import java.awt.event.*;
 import java.net.*;
import java.io.*;
 public class E11_1c extends Frame implements 	ActionListener
{
  Socket ClientSocket;
  PrintStream os;
  DataInputStream is; 
  String s;
  Label Mylabel=new Label("欢迎使用本机提供的信	息");
  TextArea textArea;
  Button MyButton = new Button("发送");
  public E11_1c( )
  {
    setTitle("Client Window");//建立并显示与Server					           通信的信息窗口
    setLayout(new BorderLayout( ));
    this.addWindowListener(new 	WinAdptClient(this));
    MyButton.addActionListener(this);
    textArea=new TextArea(20,50);
    add("North",Mylabel);
    add("South",MyButton);
    add("Center",textArea);
    setResizable(false);
    pack( );
    show( );
    connect( );                           //与Server端连接通信
  }
public void connect( )
{
  try{   
  ClientSocket=new Socket("localhost",8000);   //连向Server主机的8000端口
  os=new PrintStream(
  new BufferedOutputStream(ClientSocket.getOutputStream( )));
  is=new DataInputStream(
  new BufferedInputStream(ClientSocket.getInputStream( )));
  s=is.readLine( );//从Server端读入数据
  textArea.appendText(s+"\n");
}
 catch(Exception e){}    
}
public void actionPerformed(ActionEvent e)
{//当点击按钮时向Server端发送信息
   if(e.getSource( )==MyButton)
 {
try{
os.print(textArea.getText( ));
os.flush( );               
 }
 catch(Exception ex){}
}
}
 public static void main(String args[])
 {
new E11_1c( );
 }
}
 class WinAdptClient extends WindowAdapter
{
E11_1c m_Parent;

 WinAdptClient(E11_1c p)
 {
 m_Parent = p;
}
 public void windowClosing(WindowEvent e)
  {
 try{//关闭窗口前先向Server端发送结束信息,并关闭各输入输出流与连接
  m_Parent.os.println("Bye");
m_Parent.os.flush( );
 m_Parent.is.close( );
 m_Parent.os.close( );
 m_Parent.ClientSocket.close( );
 m_Parent.dispose( );
 System.exit(0);
 }catch(Exception ex){}
 }    
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?