📄 clientchat.java
字号:
import java.awt.*;
import java.io.*;
import java.net.*;
import java.applet.*;
import java.util.Hashtable;
import javax.swing.JOptionPane;
public class ClientChat extends Applet implements Runnable
{
final static int PORT = 1234;
Socket socket = null;
DataInputStream in = null;
DataOutputStream out = null;
InputNameTextField nameField = null;
static ChatArea chatArea = null;
Hashtable listTable;
Panel north, center;
Thread chatThread;
public void init()
{
int width = getSize().width;
int height = getSize().height;
listTable = new Hashtable();
setLayout(new BorderLayout());
nameField = new InputNameTextField(listTable);
int h = nameField.getSize().height;
chatArea = new ChatArea("", listTable, width, height - (h + 5));
chatArea.setVisible(false);
north = new Panel(new FlowLayout(FlowLayout.LEFT));
center = new Panel();
north.add(nameField);
center.add(chatArea);
add(north, BorderLayout.NORTH);
add(center, BorderLayout.CENTER);
validate();
}
public void start()
{
if (socket != null && in != null && out != null) // 一般情况下都为null,清理
{
try
{
socket.close();
in.close();
out.close();
} catch (IOException e)
{
// TODO 自动生成 catch 块
e.printStackTrace();
}
chatArea.setVisible(false);
}
try
{
socket = new Socket(this.getCodeBase().getHost(), PORT);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
} catch (IOException ee)
{
// ChatArea.remind.setText("无法连接服务器!");
JOptionPane.showMessageDialog(null, "无法连接服务器!\n请检查是否已连上服务器",
"连接错误!", JOptionPane.ERROR_MESSAGE);
stop();
}
if (socket != null)
{
InetAddress address = socket.getInetAddress();
// remindLabel.setText("成功连接服务器:" + address);
nameField.setSocketConnection(socket, in, out);
north.validate();
}
if (chatThread == null)
{
chatThread = new Thread(this);
chatThread.start();
}
}
public void stop()
{
try
{
socket.close();
in.close();
out.close();
nameField.setVisible(false); //
chatArea.setVisible(false); //
chatThread = null;
} catch (IOException e)
{
this.showStatus(e.toString());
}
}
public void run()
{
while (chatThread != null) // 可以聊天,则显示聊天界面
{
if (nameField.getOkToChat() == true)
{
chatArea.setVisible(true);
chatArea.setName(nameField.getName());
chatArea.setSocketConnection(socket, in, out);
center.validate();
break;
}
try
{
Thread.sleep(200);
} catch (Exception e)
{
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -