- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在用 Java 实现一个基本的聊天服务器。实际上我完成了基本的事情并试图改进它。
现在我想尝试制作一个显示谁在线的列表。我有个问题。我在 JTextPane
组件上获取字符串,当我按“ENTER”时它发送消息但文本光标转到下一行。我使用 setCaretPosition(0);
但它没有用。
您可以看到下图并理解问题。
这是我的服务器和服务器线程代码;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Server {
private ServerSocket ss;
private Socket s;
Map<Socket,DataOutputStream> list = new HashMap<Socket,DataOutputStream>();
public Server(int port_number) throws IOException{
create_Server(port_number);
}
public static void main(String[] args) throws IOException {
int port_number=23;
new Server(port_number);
}
private void create_Server(int port_number) throws IOException{
ss = new ServerSocket(port_number);
System.out.println("Server is ready!");
while(true){
s=ss.accept();
System.out.println(s.getLocalAddress().getHostName() + " was connected!");
send_con_mes();
list.put(s,new DataOutputStream(s.getOutputStream()) );
new ServerThread(s,this).start();
}
}
private void send_con_mes() throws IOException{
Set<Socket> sckt_list = list.keySet();
Iterator<Socket> itr = sckt_list.iterator();
DataOutputStream daos;
String str;
Socket sckt;
while(itr.hasNext()){
sckt=itr.next();
str = sckt.getLocalAddress().getHostName() + " was connected..." ;
daos = list.get(sckt);
daos.writeUTF(str);
}
}
public void send_to_All(String msg, Socket socket) throws IOException{
synchronized(list){
Set<Socket> sckt_list = list.keySet();
Iterator<Socket> itr = sckt_list.iterator();
DataOutputStream daos;
while(itr.hasNext()){
Socket sck = itr.next();
if(sck!=socket){
daos = list.get(sck);
daos.writeUTF(msg);
}
}
}
}
public void remove_Connection(Socket s) throws IOException{
synchronized(list){
list.remove(s);
System.out.println(s.getLocalAddress().getHostName() + " was disconnected!");
s.close();
}
}
}
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
public class ServerThread extends Thread {
private Socket s;
private Server srv;
public ServerThread(Socket s,Server srv){
this.s = s;
this.srv = srv;
}
@Override
public void run() {
String msg;
DataInputStream dis;
try {
dis = new DataInputStream(s.getInputStream());
while(true){
msg = dis.readUTF();
srv.send_to_All(msg, s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
srv.remove_Connection(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
所以我想我必须在 server.java 中实现列表,但问题是我如何传递列表并在 client.java 中使用它。这是我的客户端代码:
import java.awt.Frame;
import java.awt.event.KeyEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Client.java
*
* Created on 02.Eyl.2011, 16:46:44
*/
/**
*
* @author BURAKTAS
*/
public class Client extends javax.swing.JFrame implements Runnable {
private DataOutputStream dos;
private DataInputStream dis;
private Socket s;
private String Client_name;
private String Ip_addr;
private DefaultListModel listModel=new DefaultListModel();
/** Creates new form Client */
public Client() {
initComponents();
Screen.setEditable(false);
acc_list.setVisibleRowCount(6);
listModel.addElement(Client_name);
start_Chat();
}
@Override
public void run() {
try {
while(true){
String message = dis.readUTF();
Screen.append(message + "\n");
}
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void start_Chat() {
try {
Ip_addr = JOptionPane.showInputDialog("Enter the IP number of the server to connect : ");
s = new Socket(Ip_addr, 23);
Client_name = JOptionPane.showInputDialog("Enter your Nickname : ");
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
new Thread(Client.this).start();
} catch (UnknownHostException ex) {
JOptionPane.showMessageDialog(rootPane, "Socket can not connected", "ERROR", JOptionPane.ERROR_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(rootPane, "Socket can not connected", "ERROR", JOptionPane.ERROR_MESSAGE);
start_Chat();
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
font_chooser = new javax.swing.JColorChooser();
jScrollPane1 = new javax.swing.JScrollPane();
Screen = new javax.swing.JTextArea();
Send_Button = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
acc_list = new javax.swing.JList();
disco_button = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
Text_Field = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("BrkChat_Server vs 1.0");
setResizable(false);
Screen.setColumns(20);
Screen.setRows(5);
jScrollPane1.setViewportView(Screen);
Send_Button.setText("Send");
Send_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Send_ButtonActionPerformed(evt);
}
});
acc_list.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
acc_list.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
jScrollPane2.setViewportView(acc_list);
disco_button.setText("Disconnect");
disco_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
disco_buttonActionPerformed(evt);
}
});
Text_Field.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
Text_Field.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
Text_FieldKeyPressed(evt);
}
});
jScrollPane3.setViewportView(Text_Field);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 383, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(disco_button, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
.addComponent(Send_Button, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Send_Button, javax.swing.GroupLayout.DEFAULT_SIZE, 79, Short.MAX_VALUE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(disco_button, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(11, 11, 11))
);
pack();
}// </editor-fold>
private void write(){
try {
Text_Field.setCaretPosition(0);
String str = Text_Field.getText();
dos.writeUTF(Client_name + " : " + str);
Screen.append(Client_name + " : " + str + "\n");
Text_Field.setText("");
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void Send_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
write();
}
private void disco_buttonActionPerformed(java.awt.event.ActionEvent evt) {
try {
s.close();
this.setVisible(false);
System.exit(0);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void Text_FieldKeyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode()==KeyEvent.VK_ENTER){
write();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Client().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextArea Screen;
private javax.swing.JButton Send_Button;
private javax.swing.JTextPane Text_Field;
private javax.swing.JList acc_list;
private javax.swing.JButton disco_button;
private javax.swing.JColorChooser font_chooser;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
// End of variables declaration
}
如果你能帮助我,我将不胜感激。还是谢谢你。
最佳答案
这是因为您清除了监听器 keyPressed
方法中的文本字段。因此,键事件仍然存在,然后添加文本(在本例中为换行符)。快速而肮脏的解决方法是在调用 write()
之前添加一个 evt.consume();
。
关于java聊天服务器查看在线帐户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7295569/
我想知道 gmail 聊天如何允许用户连接到 AIM,然后像登录到 AIM 一样聊天。 做起来容易吗?怎么做到的? 有人知道任何类似的开源工具吗? 谢谢! 最佳答案 如果你在谈论编程,这里是源代码示例
大家好,我正在尝试制作一个游戏,两个主持人联系起来,他们将“掷硬币”,并确定谁先出局。我决定从基本代码开始。但是我真的没有主意。 Thread server2 = new Thread(new Ser
我已经创建了一个只有 1 个房间的聊天室、私有(private)消息、审核以及一切,现在一切都很好!当我测试聊天时,我意识到在聊天中输入的所有消息都会被保存,如果有很多人使用聊天,它很快就会占用 Fi
当用户键入内容并出现软键盘时,我必须保持聊天回收器 View 的当前项目可见。目前,它覆盖了聊天,我需要回收器 View 项目与键盘一起显示。 我在 list 中尝试了这些: -android:win
我有一个服务器客户端应用程序集。 (家庭作业) 到目前为止,我已经弄清楚如何让多个客户端连接到服务器并让服务器聚合客户端发送的消息,以及如何让服务器将客户端的消息发送回客户端并将其显示在聊天 Pane
如何从我的应用程序发送/接收 Facebook 聊天消息?它是用 .Net、C# 编写的。 最佳答案 如果你可以使用 C,你就可以使用 libpurple (GPL) 和 pidgin-faceboo
我正在使用启用的 Ajax-Wcf 服务开发 Asp.Net 聊天。这是一个非常简单的聊天引擎,其中消息对话框意味着一对一(单个用户),但是我不知道如何管理(以最佳方式)通知新消息可用性。例如,假设有
我的任务是通过服务器构建一个客户端到客户端的聊天程序。客户端 A 将向服务器发送一条消息,然后服务器将消息转发给客户端 B,反之亦然。所有这一切都将同时发生,直到其中一个将其关闭。我有以下程序。 服务
我创建了一个聊天,用户可以在其中输入文本的输入字段。当他输入文本并按下发送(或输入)时,文本位于输入字段上方。像这样: 我想要的:我希望输入字段位于页面底部。我使用 position: absolut
出于个人兴趣,我尝试定义一个模拟 AI,它基于他学到的信息和互联网搜索,以便提供比系统知道的更多的细节。 我举了一个 child 的例子,当他出生时他需要学习一切,他听到了很多然后提出了一些答案。他的
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 想改进这个问题?将问题更新为 on-topic对于堆栈溢出。 3年前关闭。 Improve this qu
我已经开始聊天了,但我已经将用户的 ID 硬编码到 Chat.php 中。 当他们登录站点时,我的登录名将他们的电子邮件设置为 session ( $_SESSION['email']=$email;
当用户点击像 Start a viber chat with us 这样的链接时,我试图找到一种方法来开始 viber 聊天。但到目前为止我没有找到正确的URI来做到这一点。例如,我知道我可以使用 s
我是 Javascript(纯 javascript)新手,我正在尝试创建一个执行以下操作的聊天 Controller 应用程序。 用户输入内容。 有人对我的知识库进行了后调用。 服务器响应消息。 目
已关闭。这个问题是 not about programming or software development 。目前不接受答案。 这个问题似乎不是关于 a specific programming
如果用户在 x 秒/分钟内处于非事件状态,我想结束聊天,以便我们的代理不必等待聊天自行关闭。我还想在结束聊天之前将标签附加到聊天中,以便我可以看到这是由于不活动造成的。 最佳答案 此内容归功于 j
我正在此网站中构建新网站,客户需要 24/7 实时客户支持。我想在网站上集成 Skype 聊天 聊天界面应该在客户端的网站上。 最佳答案 您可以通过在网站上放置 Skype 按钮来使用它。 http:
事实上,我只是开始积极练习 swing,以便我的理论知识能派上用场:) 我已经为聊天 GUI 实现做了很多工作,但最终遇到了一些问题。所以我决定从头开始重新设计聊天 GUI,但我需要为其选择正确的组件
已关闭。这个问题是 not about programming or software development 。目前不接受答案。 这个问题似乎不是关于 a specific programming
我正在尝试进行简单的聊天,其中连接到服务器的用户发送消息,其他用户接收消息。 这是我的 html: function setupEventSource()
我是一名优秀的程序员,十分优秀!