- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在下面的代码中,我试图创建一个聊天室,但它不起作用,因为当服务器运行时,当我按下加入按钮(右侧端口和客户端)时,它什么也不做。如果我取出 actionPerformed() 方法中的线程,按钮将卡住并保持按下状态。
代码:
服务器:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class Server implements ActionListener, WindowListener {
private JButton clear;
private JButton sendToAll;
private JTextArea log;
private JTextField inpf;
private JFrame fr;
private ServerSocket ss;
private Socket sock;
private PrintWriter out;
private BufferedReader in;
private boolean accepted;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new Server().go();
} catch (Throwable e) {
ReportError(e);
}
}
private void go() throws Throwable {
accepted = false;
Starter s = new Starter();
int port = s.getPort();
ss = new ServerSocket(port);
fr = new JFrame("Consle Port: "+String.valueOf(port));
fr.setDefaultCloseOperation(0);
fr.addWindowListener(this);
clear = new JButton("Clear Consle");
sendToAll = new JButton("Send");
clear.addActionListener(this);
sendToAll.addActionListener(this);
inpf = new JTextField(20);
log = new JTextArea();
log.setEditable(false);
JScrollPane scr = new JScrollPane();
scr.setViewportView(log);
fr.setLayout(new GridLayout(2, 2));
fr.add(scr);
fr.add(clear);
JPanel pan = new JPanel();
pan.add(inpf);
JPanel p = new JPanel();
p.add(sendToAll);
fr.add(pan);
fr.add(p);
fr.setLocationRelativeTo(null);
fr.setSize(500, 500);
fr.setVisible(true);
log.append("Wating for one client...");
sock = ss.accept();
accepted = true;
log.append("A client has joined! Server now running!");
String str = "";
out = new PrintWriter(sock.getOutputStream());
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
while((str = in.readLine()) != null) {
out.print(str+"\n");
out.flush();
log.append(str+"\n");
}
}
@Override public void actionPerformed(ActionEvent e) {
if(e.getSource() == clear) {
log.setText("");
}else if(e.getSource() == sendToAll) {
if(out != null) {
out.print("Server: "+inpf.getText()+"\n");
out.flush();
} else
JOptionPane.showMessageDialog(null, "Nobody has joined. You are not allowed to send messages.", "No sending messages.", JOptionPane.INFORMATION_MESSAGE);
inpf.setText("");
}
}
@Override public void windowOpened(WindowEvent e) {}
@Override public void windowClosing(WindowEvent e) {
try {
int i = 0;
if(accepted) {
i = JOptionPane.showConfirmDialog(null, "Are you sure you want to shut down the server?", "Shut Down", JOptionPane.YES_NO_OPTION);
if(i == 0) {
out.print("server.exit\n"); //Remember to encrypt "server.exit"
ss.close();
sock.close();
}
} else
i = JOptionPane.showConfirmDialog(null, "Nobody has joined. Are you sure you want to exit?", "Nobody Joined", JOptionPane.YES_NO_OPTION);
if(i == 0)
System.exit(0);
} catch (Throwable e1) {
ReportError(e1);
}
}
@Override public void windowClosed(WindowEvent e) {}
@Override public void windowIconified(WindowEvent e) {}
@Override public void windowDeiconified(WindowEvent e) {}
@Override public void windowActivated(WindowEvent e) {}
@Override public void windowDeactivated(WindowEvent e) {}
protected static void ReportError(Throwable error) {
if(error.getMessage() != null && error.getCause() != null)
JOptionPane.showMessageDialog(null, "This happend because "+error.getCause()+". A deatial message has been included: "+error.getMessage()+". Terminating...", error.getClass().getName(), JOptionPane.ERROR_MESSAGE);
else if(error.getMessage() != null && error.getCause() == null)
JOptionPane.showMessageDialog(null, "This happend because "+error.getCause()+". No deatial message was included. Terminating...", error.getClass().getName(), JOptionPane.ERROR_MESSAGE);
else if(error.getMessage() == null && error.getCause() != null)
JOptionPane.showMessageDialog(null, "It is unknown why this error occured, but a deatial message has been included: "+error.getMessage()+". Terminating...", error.getClass().getName(), JOptionPane.ERROR_MESSAGE);
if(error.getMessage() == null && error.getCause() == null)
JOptionPane.showMessageDialog(null, "A "+error.getClass().getName()+" has occured. Terminating...", error.getClass().getName(), JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
private class Starter extends JFrame implements ActionListener {
private static final long serialVersionUID = -1841997198914785917L;
private JButton conf;
private JTextField pf;
public Starter() {
initGui();
desGui();
}
private void initGui() {
conf = new JButton("Host");
conf.addActionListener(this);
pf = new JTextField("Port", 7);
}
private void desGui() {
setLayout(new GridLayout(2, 1));
add(pf);
add(conf);
setTitle("Host a Server");
setDefaultCloseOperation(3);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public int getPort() {
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
ReportError(e);
}
}
int i = 0;
try {
i = Integer.parseInt(pf.getText());
}catch(NumberFormatException e) {
JOptionPane.showMessageDialog(this, "The port entered was not valid. Terminating...", "Port Not Valid", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
dispose();
return i;
}
@Override public void actionPerformed(ActionEvent e) {
synchronized (this) {
this.notifyAll();
}
}
}
}
客户:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class Client implements WindowListener, KeyListener, ActionListener {
private JButton join;
private JButton clelog;
private JButton send;
private JTextField portf;
private JTextField clientf;
private JTextField mesf;
private JTextArea log;
private JFrame jfr;
private Socket sock;
private BufferedReader in;
private PrintWriter out;
private Client() throws Throwable {
jfr = new JFrame();
jfr.setLayout(new GridLayout(3, 1));
join = new JButton("Join");
join.addActionListener(this);
portf = new JTextField("Port", 7);
clientf = new JTextField("Client", 15);
jfr.add(portf);
jfr.add(clientf);
jfr.add(join);
jfr.pack();
jfr.setLocationRelativeTo(null);
jfr.setVisible(true);
}
@Override public void actionPerformed(ActionEvent e) {
if(e.getSource() == join)
SwingUtilities.invokeLater(new Runnable() {
public void run() {
join();
}
});
else if(e.getSource() == send)
send(mesf.getText());
else if(e.getSource() == clelog)
log.setText("");
}
private void join() {
jfr.dispose();
try {
Integer.parseInt(portf.getText());
}catch(NumberFormatException e2) {
JOptionPane.showMessageDialog(jfr, "The port entered was not valid. Terminating...", "Port Not Valid", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
if(sock != null)
try {
sock.close();
} catch (IOException e1) {
reportError(e1);
}
try {
runProgram();
} catch (Throwable e1) {
reportError(e1);
}
}
private void runProgram() throws Throwable{
JFrame rfr = new JFrame("Consle");
rfr.setDefaultCloseOperation(0);
rfr.addWindowListener(this);
rfr.setLayout(new GridLayout(2, 2));
log = new JTextArea();
log.setEditable(false);
rfr.add(log);
mesf = new JTextField(20);
clelog = new JButton("Clear Consle");
send = new JButton("Send");
send.addActionListener(this);
clelog.addActionListener(this);
rfr.add(clelog);
JPanel pan = new JPanel();
JPanel p = new JPanel();
pan.add(mesf);
p.add(send);
rfr.add(pan);
rfr.add(p);
rfr.pack();
rfr.setLocationRelativeTo(null);
rfr.setVisible(true);
sock = new Socket(clientf.getText(), Integer.parseInt(portf.getText()));
out = new PrintWriter(sock.getOutputStream());
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String inp = "";
while((inp = in.readLine()) != null) {
log.append(inp+"\n");
}
}
@Override public void keyTyped(KeyEvent e) {}
@Override public void keyPressed(KeyEvent e) {}
@Override public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
send(mesf.getText());
}
}
private void send(String text) {
out.print(mesf.getText()+"\n");
mesf.setText("");
}
@Override public void windowOpened(WindowEvent e) {}
@Override public void windowClosing(WindowEvent e) {
}
@Override public void windowClosed(WindowEvent e) {}
@Override public void windowIconified(WindowEvent e) {}
@Override public void windowDeiconified(WindowEvent e) {}
@Override public void windowActivated(WindowEvent e) {}
@Override public void windowDeactivated(WindowEvent e) {}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new Client();
}catch(NumberFormatException e) {
JOptionPane.showMessageDialog(null, "The port you entered is not valid. Terminating...", "Port not valid", 0);
System.exit(0);
}catch(Throwable e) {
reportError(e);
}
}
protected static void reportError(Throwable error) {
if(error.getMessage() != null && error.getCause() != null)
JOptionPane.showMessageDialog(null, "This happend because "+error.getCause()+". A deatial message has been included: "+error.getMessage()+". Terminating...", error.getClass().getName(), JOptionPane.ERROR_MESSAGE);
else if(error.getMessage() != null && error.getCause() == null)
JOptionPane.showMessageDialog(null, "This happend because "+error.getCause()+". No deatial message was included. Terminating...", error.getClass().getName(), JOptionPane.ERROR_MESSAGE);
else if(error.getMessage() == null && error.getCause() != null)
JOptionPane.showMessageDialog(null, "It is unknown why this error occured, but a deatial message has been included: "+error.getMessage()+". Terminating...", error.getClass().getName(), JOptionPane.ERROR_MESSAGE);
else if(error.getMessage() == null && error.getCause() == null)
JOptionPane.showMessageDialog(null, "A "+error.getClass().getName()+" has occured. Terminating...", error.getClass().getName(), JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
最佳答案
您正在事件调度线程上执行所有 I/O,这会阻止所有 UI 更新。您需要生成一个单独的线程来监听套接字上的传入消息,然后通过 EventQueue
发送命令来更新 UI。
关于java - 在java中连接时客户端卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20364768/
我需要将文本放在 中在一个 Div 中,在另一个 Div 中,在另一个 Div 中。所以这是它的样子: #document Change PIN
奇怪的事情发生了。 我有一个基本的 html 代码。 html,头部, body 。(因为我收到了一些反对票,这里是完整的代码) 这是我的CSS: html { backgroun
我正在尝试将 Assets 中的一组图像加载到 UICollectionview 中存在的 ImageView 中,但每当我运行应用程序时它都会显示错误。而且也没有显示图像。 我在ViewDidLoa
我需要根据带参数的 perl 脚本的输出更改一些环境变量。在 tcsh 中,我可以使用别名命令来评估 perl 脚本的输出。 tcsh: alias setsdk 'eval `/localhome/
我使用 Windows 身份验证创建了一个新的 Blazor(服务器端)应用程序,并使用 IIS Express 运行它。它将显示一条消息“Hello Domain\User!”来自右上方的以下 Ra
这是我的方法 void login(Event event);我想知道 Kotlin 中应该如何 最佳答案 在 Kotlin 中通配符运算符是 * 。它指示编译器它是未知的,但一旦知道,就不会有其他类
看下面的代码 for story in book if story.title.length < 140 - var story
我正在尝试用 C 语言学习字符串处理。我写了一个程序,它存储了一些音乐轨道,并帮助用户检查他/她想到的歌曲是否存在于存储的轨道中。这是通过要求用户输入一串字符来完成的。然后程序使用 strstr()
我正在学习 sscanf 并遇到如下格式字符串: sscanf("%[^:]:%[^*=]%*[*=]%n",a,b,&c); 我理解 %[^:] 部分意味着扫描直到遇到 ':' 并将其分配给 a。:
def char_check(x,y): if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):
我有一种情况,我想将文本文件中的现有行包含到一个新 block 中。 line 1 line 2 line in block line 3 line 4 应该变成 line 1 line 2 line
我有一个新项目,我正在尝试设置 Django 调试工具栏。首先,我尝试了快速设置,它只涉及将 'debug_toolbar' 添加到我的已安装应用程序列表中。有了这个,当我转到我的根 URL 时,调试
在 Matlab 中,如果我有一个函数 f,例如签名是 f(a,b,c),我可以创建一个只有一个变量 b 的函数,它将使用固定的 a=a1 和 c=c1 调用 f: g = @(b) f(a1, b,
我不明白为什么 ForEach 中的元素之间有多余的垂直间距在 VStack 里面在 ScrollView 里面使用 GeometryReader 时渲染自定义水平分隔线。 Scrol
我想知道,是否有关于何时使用 session 和 cookie 的指南或最佳实践? 什么应该和什么不应该存储在其中?谢谢! 最佳答案 这些文档很好地了解了 session cookie 的安全问题以及
我在 scipy/numpy 中有一个 Nx3 矩阵,我想用它制作一个 3 维条形图,其中 X 轴和 Y 轴由矩阵的第一列和第二列的值、高度确定每个条形的 是矩阵中的第三列,条形的数量由 N 确定。
假设我用两种不同的方式初始化信号量 sem_init(&randomsem,0,1) sem_init(&randomsem,0,0) 现在, sem_wait(&randomsem) 在这两种情况下
我怀疑该值如何存储在“WORD”中,因为 PStr 包含实际输出。? 既然Pstr中存储的是小写到大写的字母,那么在printf中如何将其给出为“WORD”。有人可以吗?解释一下? #include
我有一个 3x3 数组: var my_array = [[0,1,2], [3,4,5], [6,7,8]]; 并想获得它的第一个 2
我意识到您可以使用如下方式轻松检查焦点: var hasFocus = true; $(window).blur(function(){ hasFocus = false; }); $(win
我是一名优秀的程序员,十分优秀!