❶ java简单C/S聊天室程序~~~
package JavaNet;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ClientOneToOne_ClientFrame extends JFrame {
private JTextField tf_newUser;
private JList user_list;
private JTextArea ta_info;
private JTextField tf_send;
PrintWriter out;// 声明输出流对象
private boolean loginFlag = false;// 为true时表示已经登录,为false时表示未登录
/**
* Launch the application
*
* @param args
*/
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ClientOneToOne_ClientFrame frame = new ClientOneToOne_ClientFrame();
frame.setVisible(true);
frame.createClientSocket();// 调用方法创建套接字对象
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void createClientSocket() {
try {
Socket socket = new Socket("127.0.0.1", 1978);// 创建套接字对象
out = new PrintWriter(socket.getOutputStream(), true);// 创建输出流对象
new ClientThread(socket).start();// 创建并启动线程对象
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
class ClientThread extends Thread {
Socket socket;
public ClientThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));// 创建输入流对象
DefaultComboBoxModel model = (DefaultComboBoxModel) user_list
.getModel();// 获得列表框的模型
while (true) {
String info = in.readLine().trim();// 读取信息
if (!info.startsWith("MSG:")) {
boolean itemFlag = false;// 标记是否为列表框添加列表项,为true不添加,为false添加
for (int i = 0; i < model.getSize(); i++) {
if (info.equals((String) model.getElementAt(i))) {
itemFlag = true;
}
}
if (!itemFlag) {
model.addElement(info);// 添加列表项
} else {
itemFlag = false;
}
} else {
ta_info.append(info + "\n");// 在文本域中显示信息
if (info.equals("88")) {
break;// 结束线程
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void send() {
if (!loginFlag) {
JOptionPane.showMessageDialog(null, "请先登录。");
return;
}
String sendUserName = tf_newUser.getText().trim();
String info = tf_send.getText();// 获得输入的信息
if (info.equals("")) {
return;// 如果没输入信息则返回,即不发送
}
String receiveUserName = (String) user_list.getSelectedValue();// 获得接收信息的用户
String msg = sendUserName + ":发送给:" + receiveUserName + ":的信息是: "
+ info;// 定义发送的信息
if (info.equals("88")) {
System.exit(0);// 如果没输入信息是88,则退出
}
out.println(msg);// 发送信息
out.flush();// 刷新输出缓冲区
tf_send.setText(null);// 清空文本框
}
/**
* Create the frame
*/
public ClientOneToOne_ClientFrame() {
super();
setTitle("客户端一对一通信——客户端程序");
setBounds(100, 100, 385, 288);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.SOUTH);
final JLabel label = new JLabel();
label.setText("输入聊天内容:");
panel.add(label);
tf_send = new JTextField();
tf_send.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
send();// 调用方法发送信息
}
});
tf_send.setPreferredSize(new Dimension(180, 25));
panel.add(tf_send);
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
send();// 调用方法发送信息
}
});
button.setText("发 送");
panel.add(button);
final JSplitPane splitPane = new JSplitPane();
splitPane.setDividerLocation(100);
getContentPane().add(splitPane, BorderLayout.CENTER);
final JScrollPane scrollPane = new JScrollPane();
splitPane.setRightComponent(scrollPane);
ta_info = new JTextArea();
scrollPane.setViewportView(ta_info);
final JScrollPane scrollPane_1 = new JScrollPane();
splitPane.setLeftComponent(scrollPane_1);
user_list = new JList();
user_list.setModel(new DefaultComboBoxModel(new String[] { "" }));
scrollPane_1.setViewportView(user_list);
final JPanel panel_1 = new JPanel();
getContentPane().add(panel_1, BorderLayout.NORTH);
final JLabel label_1 = new JLabel();
label_1.setText("输入用户名称:");
panel_1.add(label_1);
tf_newUser = new JTextField();
tf_newUser.setPreferredSize(new Dimension(180, 25));
panel_1.add(tf_newUser);
final JButton button_1 = new JButton();
button_1.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
if (loginFlag) {
JOptionPane.showMessageDialog(null, "在同一窗口只能登录一次。");
return;
}
String userName = tf_newUser.getText().trim();// 获得登录用户名
out.println("用户:" + userName);// 发送登录用户的名称
out.flush();// 刷新输出缓冲区
tf_newUser.setEnabled(false);
loginFlag = true;
}
});
button_1.setText("登 录");
panel_1.add(button_1);
}
}
package JavaNet;
import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ClientOneToOne_ServerFrame extends JFrame {
private JTextArea ta_info;
private ServerSocket server; // 声明ServerSocket对象
private Socket socket; // 声明Socket对象socket
private Hashtable<String, Socket> map = new Hashtable<String, Socket>();// 用于存储连接到服务器的用户和客户端套接字对象
public void createSocket() {
try {
server = new ServerSocket(1978);
while (true) {
ta_info.append("等待新客户连接......\n");
socket = server.accept();// 创建套接字对象
ta_info.append("客户端连接成功。" + socket + "\n");
new ServerThread(socket).start();// 创建并启动线程对象
}
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread extends Thread {
Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));// 创建输入流对象
while (true) {
String info = in.readLine();// 读取信息
String key = "";
if (info.startsWith("用户:")) {// 添加登录用户到客户端列表
key = info.substring(3, info.length());// 获得用户名并作为键使用
map.put(key, socket);// 添加键值对
Set<String> set = map.keySet();// 获得集合中所有键的Set视图
Iterator<String> keyIt = set.iterator();// 获得所有键的迭代器
while (keyIt.hasNext()) {
String receiveKey = keyIt.next();// 获得表示接收信息的键
Socket s = map.get(receiveKey);// 获得与该键对应的套接字对象
PrintWriter out = new PrintWriter(s
.getOutputStream(), true);// 创建输出流对象
Iterator<String> keyIt1 = set.iterator();// 获得所有键的迭代器
while (keyIt1.hasNext()) {
String receiveKey1 = keyIt1.next();// 获得键,用于向客户端添加用户列表
out.println(receiveKey1);// 发送信息
out.flush();// 刷新输出缓冲区
}
}
} else {// 转发接收的消息
key = info.substring(info.indexOf(":发送给:") + 5, info
.indexOf(":的信息是:"));// 获得接收方的key值,即接收方的用户名
String sendUser = info.substring(0, info
.indexOf(":发送给:"));// 获得发送方的key值,即发送方的用户名
Set<String> set = map.keySet();// 获得集合中所有键的Set视图
Iterator<String> keyIt = set.iterator();// 获得所有键的迭代器
while (keyIt.hasNext()) {
String receiveKey = keyIt.next();// 获得表示接收信息的键
if (key.equals(receiveKey)
&& !sendUser.equals(receiveKey)) {// 如果是发送方,但不是用户本身
Socket s = map.get(receiveKey);// 获得与该键对应的套接字对象
PrintWriter out = new PrintWriter(s
.getOutputStream(), true);// 创建输出流对象
out.println("MSG:"+info);// 发送信息
out.flush();// 刷新输出缓冲区
}
}
}
}
} catch (IOException e) {
ta_info.append(socket + "已经退出。\n");
}
}
}
/**
* Launch the application
*
* @param args
*/
public static void main(String args[]) {
ClientOneToOne_ServerFrame frame = new ClientOneToOne_ServerFrame();
frame.setVisible(true);
frame.createSocket();
}
/**
* Create the frame
*/
public ClientOneToOne_ServerFrame() {
super();
setTitle("客户端一对一通信——服务器端程序");
setBounds(100, 100, 385, 266);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);
ta_info = new JTextArea();
scrollPane.setViewportView(ta_info);
}
}
❷ 用JAVA 编写简单网络聊天程序
Java编写的程序,为什么要遵循windows命名规范?再说,什么是windows命名规范?匈牙利命名法?分太少,不干,我说说思路吧。
点对点聊天,双方都是服务器,也都是客户端,当终端发送信息时就是客户,接收信息就是服务器,可能要有两个连接。简单的程序应该不难,毕竟Java比较简单。
❸ java的问题,一个简单的聊天程序
lz 你好
具体代码如下:
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
publicclassChatextendsJFrame{
privateJLabelenter,start;
privateJTextFieldinput;
privateJTextAreaoutput;
publicChat(){
super("小程序查看器:Client.class");
enter=newJLabel("<html>小程序<br>EnterText</html>");
enter.setFont(newFont("宋体",Font.PLAIN,12));
start=newJLabel("小程序已启动。");
start.setFont(newFont("宋体",Font.PLAIN,12));
input=newJTextField(30);
output=newJTextArea(10,35);
output.setEditable(false);
input.addKeyListener(newKeyAdapter(){
publicvoidkeyPressed(KeyEvente){
if(e.getKeyCode()==10){
output.append(input.getText()+" ");
}
}
});
setLayout(newFlowLayout(FlowLayout.LEFT,1,1));
getContentPane().add(enter);
getContentPane().add(input);
getContentPane().add(output);
getContentPane().add(start);
setLocation(300,200);
setSize(450,270);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(3);
}
publicstaticvoidmain(String[]args){
newChat();
}
}
希望能帮助你哈
❹ 如何用java做个简单的聊天程序
我这儿有一个有Java编写的聊天程序,如果你要的话,就留下邮箱,我发给你视频和代码。
❺ 如何用java做一个聊天小程序 要求使用图形用户界面,可以实现一个聊天室中多人聊天,也可以两人私聊,
给你一个简单的实现吧,注意一定要先运行MyServer.java
//MyCilent.java
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyClient extends JFrame implements ActionListener{
JTextField tf;
JTextArea tx;
JButton bt;
PrintWriter out;
public MyClient(){
tf=new JTextField(20);
tx=new JTextArea();
tx.setLineWrap(true);
tx.setWrapStyleWord(true);
JPanel pan=new JPanel();
JScrollPane jsp=new JScrollPane(tx);
add(jsp,"Center");
bt=new JButton("SEND");
bt.addActionListener(this);
pan.add(tf);
pan.add(bt);
add(pan,"South");
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
setTitle("THE CLIENT");
setSize(400,300);
setVisible(true);
try{
Socket socket=new Socket("127.0.0.1",1680);
out=new PrintWriter(socket.getOutputStream(),true);
InputStreamReader in = new InputStreamReader(socket.getInputStream());
BufferedReader sin=new BufferedReader(in);
String s;
while(true){
s=sin.readLine();
tx.append("#Server Said#: "+s+"\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==bt){
tx.append("@Client Said@: "+tf.getText()+"\n");
out.println(tf.getText());
tf.setText("");
}
}
public static void main(String[] args){
MyClient mct = new MyClient();
}
}
//MyServer.java
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyServer extends JFrame implements ActionListener{
JTextField tf;
JTextArea tx;
JButton bt;
JScrollPane jsp;
JPanel pan;
PrintWriter out;
public MyServer(){
tx=new JTextArea();
tx.setLineWrap(true);
tx.setWrapStyleWord(true);
jsp=new JScrollPane(tx);
tf=new JTextField(20);
bt=new JButton("SEND");
bt.addActionListener(this);
pan=new JPanel();
pan.add(tf);
pan.add(bt);
add(pan,"South");
add(jsp,"Center");
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
setTitle("THE SERVER");
setSize(400,300);
setVisible(true);
try{
ServerSocket server = new ServerSocket(1680);
Socket socket = server.accept();
InputStreamReader in = new InputStreamReader(socket.getInputStream());
BufferedReader sin=new BufferedReader(in);
out=new PrintWriter(socket.getOutputStream(),true);
while(true){
String s=sin.readLine();
tx.append("@Client Said@: "+s+"\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==bt){
String st = tf.getText();
tx.append("#Server Said#: "+st+"\n");
out.println(st);
tf.setText("");
}
}
public static void main(String[] args){
MyServer msr = new MyServer();
}
}
❻ 用JAVA编写的简单的聊天工具程序及解释
控制台简单聊天工具
服务端的代码
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Server {
public static int PORT = 1007;
private ServerSocket server;
public Server() throws IOException {
server = new ServerSocket(PORT);
}
public static void main(String[] args) throws Exception {
System.out.println("--Server--");
Server server = new Server();
server.accept();
}
public void accept() throws IOException {
Socket client = server.accept();//等待客户端的连接
getInfo(client.getInputStream());//启动等待消息线程
toInfo(client.getOutputStream());//启动发送消息线程
}
//等待客户端发送消息
public void getInfo(InputStream in) throws IOException {
final Scanner sc = new Scanner(in);//获取客户端的输入流
new Thread() {
@Override
public void run() {
while(true) {
if(sc.hasNextLine()) {//如果客户端有发送消息过来
System.out.println("Client:" + sc.nextLine());//打印客户端的消息
}
}
}
}.start();
}
//发送消息到客户端
public void toInfo(OutputStream out) throws IOException {
final PrintWriter pw = new PrintWriter(out, true);//获取客户端的输出流,自动清空缓存的内容
final Scanner sc = new Scanner(System.in);//获取控制台的标准输入流,从控制台输入数据
new Thread() {
@Override
public void run() {
while(true) {
pw.println(sc.nextLine());//将输入的数据发送给客户端
}
}
}.start();
}
}
客户端的代码
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception, IOException {
System.out.println("--Client--");
Client client = new Client();
client.connection("localhost", Server.PORT);
}
public void connection(String host, int port) throws IOException {
Socket client = new Socket(host, port);
getInfo(client.getInputStream());
toInfo(client.getOutputStream());
}
public void getInfo(InputStream in) throws IOException {
final Scanner sc = new Scanner(in);
new Thread() {
@Override
public void run() {
while(true) {
if(sc.hasNextLine()) {
System.out.println("Server:" + sc.nextLine());
}
}
}
}.start();
}
public void toInfo(OutputStream out) throws IOException {
final PrintWriter pw = new PrintWriter(out, true);
final Scanner sc = new Scanner(System.in);
new Thread() {
@Override
public void run() {
while(true) {
pw.println(sc.nextLine());
}
}
}.start();
}
}
❼ 用JAVA 编写简单网络聊天程序
/**
* 基于UDP协议的聊天程序
*
* 2007.9.18
* */
//导入包
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
public class Chat extends JFrame implements ActionListener
{
//广播地址或者对方的地址
public static final String sendIP = "172.18.8.255";
//发送端口9527
public static final int sendPort = 9527;
JPanel p = new JPanel();
List lst = new List(); //消息显示
JTextField txtIP = new JTextField(18); //填写IP地址
JTextField txtMSG = new JTextField(20); //填写发送消息
JLabel lblIP = new JLabel("IP地址:");
JLabel lblMSG = new JLabel("消息:");
JButton btnSend = new JButton("发送");
byte [] buf;
//定义DatagramSocket的对象必须进行异常处理
//发送和接收数据报包的套接字
DatagramSocket ds = null;
//=============构造函数=====================
public Chat()
{
CreateInterFace();
//注册消息框监听器
txtMSG.addActionListener(this);
btnSend.addActionListener(this);
try
{
//端口:9527
ds =new DatagramSocket(sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
//============接受消息============
//匿名类
new Thread(new Runnable()
{
public void run()
{
byte buf[] = new byte[1024];
//表示接受数据报包
while(true)
{
try
{
DatagramPacket dp = new DatagramPacket(buf,1024,InetAddress.getByName(txtIP.getText()),sendPort);
ds.receive(dp);
lst.add("【消息来自】◆" + dp.getAddress().getHostAddress() + "◆"+"【说】:" + new String (buf,0,dp.getLength()) /*+ dp.getPort()*/,0);
}
catch(Exception e)
{
if(ds.isClosed())
{
e.printStackTrace();
}
}
}
}
}).start();
//关闭窗体事件
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.out.println("test");
int n=JOptionPane.showConfirmDialog(null,"是否要退出?","退出",JOptionPane.YES_NO_OPTION);
if(n==JOptionPane.YES_OPTION)
{
dispose();
System.exit(0);
ds.close();//关闭ds对象//关闭数据报套接字
}
}
});
}
//界面设计布局
public void CreateInterFace()
{
this.add(lst,BorderLayout.CENTER);
this.add(p,BorderLayout.SOUTH);
p.add(lblIP);
p.add(txtIP);
p.add(lblMSG);
p.add(txtMSG);
p.add(btnSend);
txtIP.setText(sendIP);
//背景颜色
lst.setBackground(Color.yellow);
//JAVA默认风格
this.setUndecorated(true);
this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
this.setSize(600,500);
this.setTitle("〓聊天室〓");
this.setResizable(false);//不能改变窗体大小
this.setLocationRelativeTo(null);//窗体居中
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
txtMSG.requestFocus();//消息框得到焦点
}
//===============================Main函数===============================
public static void main(String[]args)
{
new Chat();
}
//================================发送消息===============================
//消息框回车发送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本内容
buf = txtMSG.getText().getBytes();
//判断消息框是否为空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"发送消息不能为空","提示",JOptionPane.WARNING_MESSAGE);
}
else{
try
{
InetAddress address = InetAddress.getByName(sendIP);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
ds.send(dp);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
txtMSG.setText("");//清空消息框
//点发送按钮发送消息事件
if(e.getSource()==btnSend)
{
buf = txtMSG.getText().getBytes();
try
{
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
txtMSG.setText("");//清空消息框
txtMSG.requestFocus();
}
}
}
❽ 求用java语言做一个简单的聊天程序
嗯,我这里有!你要求这样,代码很长的!邮箱也不留?怎么给你?
已经发送到你们的邮箱咯!请查收!~但愿能帮到你们!~
❾ java网络编程 实现极简单的聊天功能
在同一局域网环境是 应该是可以的! 程序里面只要将Beijing.java里的IP地址改为Shanghai这台机器的地址 ,Shanghai.java里的IP地址改为Beijing这台机器的地址,应该就OK
❿ 求艺个java 简单聊天程序
我有地
发在这里吧
两个文件。——ChatServer.java和ChatClient.java
运行的时候先启动 ChatServer ————否则就出错啦
//ChatServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
List<Client> clients = new ArrayList<Client>();
public static void main(String[] args) {
new ChatServer().start();
}
public void start() {
try {
ss = new ServerSocket(8888);
started = true;
} catch (BindException e) {
System.out.println("端口使用中....");
System.out.println("请关掉相关程序并重新运行服务器!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
try {
while(started) {
Socket s = ss.accept();
Client c = new Client(s);
System.out.println("a client connected!");
new Thread(c).start();
clients.add(c);
//dis.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = false;
public Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("对方退出了!我从List里面去掉了!");
//e.printStackTrace();
}
}
public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
System.out.println(str);
for(int i=0; i<clients.size(); i++) {
Client c = clients.get(i);
c.send(str);
//System.out.println(" a string send !");
}
/*
for(Iterator<Client> it = clients.iterator(); it.hasNext(); ) {
Client c = it.next();
c.send(str);
}
*/
/*
Iterator<Client> it = clients.iterator();
while(it.hasNext()) {
Client c = it.next();
c.send(str);
}
*/
}
} catch (EOFException e) {
System.out.println("Client closed!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(dis != null) dis.close();
if(dos != null) dos.close();
if(s != null) {
s.close();
//s = null;
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
//ChatClient.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame {
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
Thread tRecv = new Thread(new RecvThread());
public static void main(String[] args) {
new ChatClient().launchFrame();
}
public void launchFrame() {
setLocation(400, 300);
this.setSize(300, 300);
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
setVisible(true);
connect();
tRecv.start();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("connected!");
bConnected = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
/*
try {
bConnected = false;
tRecv.join();
} catch(InterruptedException e) {
e.printStackTrace();
} finally {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
*/
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
//taContent.setText(str);
tfTxt.setText("");
try {
//System.out.println(s);
dos.writeUTF(str);
dos.flush();
//dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private class RecvThread implements Runnable {
public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
//System.out.println(str);
taContent.setText(taContent.getText() + str + '\n');
}
} catch (SocketException e) {
System.out.println("退出了,bye!");
} catch (EOFException e) {
System.out.println("推出了,bye - bye!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}