📄 chatclient.java
字号:
/**
* <p>application name: ChatClient</p>
* <p>application describing: 聊天客户端程序</p>
* <p>copyright: Copyrigtht 2006 东软 成都Java定制班版权所有</p>
* <p>company: neusoft</p>
* <p>time: 2006.09.23</P>
*
* @author YiLiu
* @version ver 1.0
* @email:2031120624@smail.ccniit.com
*
* */
/**
* <p><code>ListMerge</code>
*
* @see java.util.List
* @see java.util.conllections
* @author YiLiu
* @version 1.0,2006-9-23
* @deprecated
* */
package Chat_9_23.bak;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.text.DateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class ChatClient extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private JTextField idField;
private JTextArea outputArea;
private JLabel label;
private JLabel label2;
private JComboBox combobox;
private JButton sendfile;
private JButton openfile;
private JButton exit;
private JPanel north;
private Socket connection;
private DataInputStream input;
private DataOutputStream output;
private int UserID;
private String Message;
//文件
private File fileName;
/**
* <p>
* <code>Method</code> 构造函数。
*
* @see java.util.conllections
* @param List <p> List </p>
*
* @author YiLiu
* @version 2.1,2006-9-19
* @since 1.0
*/
@SuppressWarnings("deprecation")
public ChatClient() {
super("Chat Client");
outputArea = new JTextArea();
outputArea.setEditable(false);
idField = new JTextField();
idField.setSize(20,5);
//添加Panel布局
FlowLayout flow = new FlowLayout(FlowLayout.CENTER,10,1);
label = new JLabel();
label2 = new JLabel();
combobox = new JComboBox();
openfile = new JButton();
sendfile = new JButton();
exit = new JButton();
label.setText("当前用户ID为: \n");
label2.setText("发送方为:");
openfile.setLabel("选择文件");
sendfile.setLabel("发送文件");
exit.setLabel("退出");
north = new JPanel();
north.setLayout(flow);
north.add(label);
north.add(label2);
north.add(combobox);
north.add(openfile);
north.add(sendfile);
north.add(exit);
//添加键盘事件
idField.addActionListener(
new ActionListener() {
// send message to server
public void actionPerformed(ActionEvent event) {
sendData(event.getActionCommand());
}
} // end anonymous inner class
); // end call to addActionListener
// 添加打开文件点击事件
openfile.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
openFile();
}
}
);
//退出事件
exit.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
closeAll();
System.exit( 0 );
}
}
);
//添加聊天布局
getContentPane().add(outputArea, BorderLayout.CENTER);
getContentPane().add(north,BorderLayout.NORTH);
getContentPane().add(idField,BorderLayout.SOUTH);
//添加垂直滚动条.
JScrollPane scroll = new JScrollPane(outputArea);
getContentPane().add(scroll, null);
setSize(600, 350);
setVisible(true);
}
private void sendData(String message) {
// send object to server
try {
String temp = InetAddress.getLocalHost().getHostName()+" >> " + message
+":"+combobox.getSelectedItem();
output.writeUTF(temp);
output.flush();
idField.setText("");
}
// process problems sending object
catch (IOException ioException) {
displayMessage("\n发送失败!");
System.exit( 1 );
}
}
private void receiveMessage()
{
try {
Message = input.readUTF();
saveLogFile(Message);
} catch (IOException e) {
e.printStackTrace();
//关闭连接
closeAll();
System.exit( 0 );
}
if(Message != null)
displayMessage(Message+"\n");
}
private void displayMessage( final String messageToDisplay )
{
// display message from event-dispatch thread of execution
SwingUtilities.invokeLater(
new Runnable() { // inner class to ensure GUI updates properly
public void run() // updates displayArea
{
outputArea.append( messageToDisplay );
outputArea.setCaretPosition(
outputArea.getText().length() );
}
} // end inner class
); // end call to SwingUtilities.invokeLater
}
public void openFile() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result = fileChooser.showOpenDialog(this);
// if user clicked Cancel button on dialog, return
if (result == JFileChooser.CANCEL_OPTION)
return;
// obtain selected file
fileName = fileChooser.getSelectedFile();
// display error is file name invalid
if (fileName == null || fileName.getName().equals(""))
JOptionPane.showMessageDialog(this, "文件名为空!",
"Invalid File Name", JOptionPane.ERROR_MESSAGE);
if (!fileName.isFile())
JOptionPane.showMessageDialog(this, "没有找到相关的文件!",
"Invalid File Name", JOptionPane.ERROR_MESSAGE);
}
public void sendFile(File fileName) {
if (fileName == null || fileName.getName().equals(""))
JOptionPane.showMessageDialog(this, "文件名为空!",
"Invalid File Name", JOptionPane.ERROR_MESSAGE);
if (!fileName.isFile())
JOptionPane.showMessageDialog(this, "没有找到相关的文件!",
"Invalid File Name", JOptionPane.ERROR_MESSAGE);
//发送文件.
}
public void saveLogFile(String message)
{
String filepath = "c:\\ChatClientMsg.txt";
File filename = new File(filepath);
PrintWriter log;
//获取系统时间
Date now = new Date();
DateFormat mediumformat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM);
String mediumDate = mediumformat.format(now);
try
{
log = new PrintWriter(new FileWriter(filename, true), true);
log.println("-------消息时间: "+mediumDate+"------");
log.println();
log.println(message);
log.println();
log.println("-----------------------------------------");
log.println();
log.println();
log.close();
} catch (IOException e)
{
e.printStackTrace();
System.err.println("无法打开文件: " + filename);
}
}
public void closeAll() {
if(input != null)
{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(output != null)
{
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection != null)
{
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void start()
{
try {
connection = new Socket( "127.0.0.1", 12345 );
// 注册输入,输出流.
input = new DataInputStream( connection.getInputStream() );
// 发送给服务器的流
output = new DataOutputStream( connection.getOutputStream() );
output.writeUTF("主机名为: "+InetAddress.getLocalHost().getHostName()+
" IP地址是: "+InetAddress.getLocalHost().getHostAddress());
//接收用户分配的ID号
UserID = input.readInt();
combobox.addItem("所有用户");
combobox.addItem("用户一");
combobox.addItem("用户二");
combobox.addItem("用户三");
label.setText("当前用户ID为 :"+(UserID+1)+" IP:");
displayMessage("客户端成功连接到服务器端!\n");
}
// catch problems setting up connection and streams
catch ( IOException ioException ) {
ioException.printStackTrace();
displayMessage("连接失败!\n");
//关闭连接
closeAll();
//System.exit( 1 );
}
Thread outputThread = new Thread( this );
outputThread.start();
} // end method start
public void run() {
while ( true ) {
receiveMessage();
}
}
public static void main(String args[]) {
ChatClient Client = new ChatClient();
Client.start();
}
}
class filesend extends Thread{
private Socket soc;
private DataInputStream input;
private DataOutputStream output;
public filesend() {
super("filesend!");
}
@SuppressWarnings("unused")
private void receiveFile(File filename) {
try
{
FileOutputStream fis = new FileOutputStream(filename);
while(true)
{
fis.write(input.readByte());
}
} catch (IOException e) {
e.printStackTrace();
System.exit( 0 );
}
}
public void start() {
// connect to server, get streams and start outputThread
try {
soc = new Socket( "127.0.0.1", 4001 );
// 注册输入,输出流.
input = new DataInputStream( soc.getInputStream() );
// 发送给服务器的流
output = new DataOutputStream( soc.getOutputStream() );
output.writeUTF("主机名为: "+InetAddress.getLocalHost().getHostName()+
" IP地址是: "+InetAddress.getLocalHost().getHostAddress());
}
// catch problems setting up connection and streams
catch ( IOException ioException ) {
ioException.printStackTrace();
//System.exit( 1 );
}
}// end of Start
public void run() {
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -