java.io小程序_JAVA小程序-------在线聊天系统

//客户端部分

importjava.awt.BorderLayout;importjava.awt.Frame;importjava.awt.TextArea;importjava.awt.TextField;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.EOFException;importjava.io.IOException;importjava.net.Socket;importjava.net.SocketException;importjava.net.UnknownHostException;public class ChatClient extendsFrame {

DataOutputStream dos= null;

Socket socket;

TextField inputChat= newTextField();

TextArea showChat= newTextArea();

DataInputStream dis= null;private static boolean isRun = false;

Thread tRecv= new Thread(newClientThread());public static voidmain(String[] args) {newChatClient().launchFrame();

}public voidlaunchFrame() {

setLocation(400, 300);

setSize(300, 300);

add(inputChat, BorderLayout.SOUTH);

add(showChat, BorderLayout.NORTH);

pack();

addWindowListener(newWindowAdapter() {

@Overridepublic voidwindowClosing(WindowEvent e) {

disconnect();

System.exit(0);

}

});

inputChat.addActionListener(newTextFieldListener());

setVisible(true);

connectToServer();

tRecv.start();

}private voidconnectToServer() {try{

socket= new Socket("127.0.0.1", 8888);

dos= newDataOutputStream(socket.getOutputStream());

dis= newDataInputStream(socket.getInputStream());

isRun= true;

}catch(UnknownHostException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

}public voiddisconnect() {try{

dos.close();

dis.close();

socket.close();

}catch(IOException e) {

e.printStackTrace();

}//关闭各种流之前必须先关闭接受线程

}private class ClientThread implementsRunnable{

@Overridepublic voidrun() {try{while(isRun){

String str=dis.readUTF();

System.out.println(str);

showChat.setText(showChat.getText()+ str +'\n');

}

}catch(SocketException e) {

System.out.println("bye");

}catch(EOFException e) {

}catch(IOException e) {

e.printStackTrace();

}

}

}private class TextFieldListener implementsActionListener {

@Overridepublic voidactionPerformed(ActionEvent e) {

String s=inputChat.getText().trim();//showChat.setText(s);

inputChat.setText("");try{

dos.writeUTF(s);

dos.flush();//dos.close();

} catch(IOException e1) {

e1.printStackTrace();

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值