📄 tcpclient2.java
字号:
/*****************************************
*程序功能:基于Socket结构的聊天程序客户端*
*程 序 员: *
*日 期:2006年4月2日 *
*版 本:1.0 *
*修改日期: *
*****************************************/
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class TcpClient2 extends WindowAdapter implements ActionListener
{
Socket client; //客户端Socket对象
boolean flag; //标记Socket对象是否已连接
BufferedReader cin; //Socket对象的字符输入流
PrintWriter cout; //Socket对象的字符输出流
Frame f; //聊天程序界面框架
Button SendButton;
Button ExitButton;
Label Label1;
Label Label2;
Label Label3;
TextArea DisplayArea;
TextField InputArea;
public TcpClient2()
{
try //try_catch对可能出现的异常进行处理
{
client=new Socket("localhost",6789); //与服务端进行连接
this.ChatFrame("客户端"); //显示在聊天程序界面
DisplayArea.append("成功建立连接!"+"\n");
flag=true;
while(flag) //提供Socket服务
{
InputStream is=client.getInputStream(); //获取Socket对象的输入流
cin =new BufferedReader(new InputStreamReader(is)); //创建字符输入流存入变量cin
OutputStream os=client.getOutputStream(); //获取Socket对象的输出流
cout =new PrintWriter(os,true); //创建字符输出流存入变量cout
String aline;
while((aline=cin.readLine())!=null) //等待接收输入流数据
{
DisplayArea.append(aline+"\n"); //将从输入流中读入的字符串添加到多行文本框
if(aline.equals("bye")) //获得结束标记时停止服务
{
flag=false;
break;
}
}
is.close(); //关闭流
os.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public void ChatFrame(String str) //构造聊天程序窗口界面
{
f=new Frame("聊天程序"+str);
f.setSize(800,600);
BorderLayout border=new BorderLayout(5,10);
f.setLayout(border);
DisplayArea=new TextArea(); //创建多行文本输入区对象
f.add(DisplayArea,border.CENTER);
DisplayArea.setEditable(false); //置DisplayArea为不可编辑状态
Panel p=new Panel(); //创建面板对象
f.add(p,border.SOUTH);
InputArea=new TextField(20); //创建文本输入行对象
SendButton=new Button("发送"); //创建按钮对象
ExitButton=new Button("关闭");
Label1=new Label("和");
Label2=new Label("聊天");
Label3=new Label("消息");
Choice choice1=new Choice();
choice1.add("LovelyPig");
choice1.add("SharpKnife");
choice1.add("Jhon");
choice1.add("Harvey");
p.add(Label1);
p.add(choice1);
p.add(Label2);
p.add(Label3);
p.add(InputArea); //把InputArea添加到p上
p.add(SendButton); //把SendButton添加到p上
p.add(ExitButton);
SendButton.addActionListener(this); //注册SendButton的Action事件
ExitButton.addActionListener(this);
InputArea.addActionListener(this); //注册InputArea的Action事件
f.setVisible(true);
f.addWindowListener(this); //注册f的Window事件
}
public void actionPerformed(ActionEvent e) //处理按钮单击事件
{
if(e.getSource()==SendButton)
{
DisplayArea.append(InputArea.getText()+"\n"); //把用户当前输入的字符串添加到多行文本框对象DisplayArea上
cout.println(InputArea.getText()); //向Socket对象的字符输出流发送字符串
InputArea.setText("");
}
if(e.getSource()==ExitButton)
{
cout.println("bye"); //向客户端发送结束标记
System.exit(0); //程序运行结束
}
}
public void windowClosing(WindowEvent e) //单击窗口关闭按钮时的处理
{
cout.println("bye"); //向客户端发送结束标记
System.exit(0); //程序运行结束
}
public static void main(String args[])
{
new TcpClient2();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -