- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
程序的流程如下:
在服务器中:
-Open new window with GUI
-Start a serversocket on port 1500
-Await a client to connect
-Accept the client
-Wait to recieve their username
-Send their client number
-Start a new Thread for the client
-Store playernames, positions and the threads
在主题中:
while 循环:
-Wait to Receive Object from client, where the Object is a Vector3f (float,float,float)
-Set the ArrayList of Vector3f, where the index is clientnumber, to equal the Object recieved from the client
-Send the client the arraylist
在客户端:
-Join server at specified ip
-Send username
-Recieve clientnumber
while 循环:
-Send Vector3f
-recieve arraylist of Vector3f
但是...我认为这会起作用。我认为客户端会正确连接,并且每个客户端都会收到其他每个玩家位置的数组列表(Vector3f)。它似乎适用于前 4 个连接的客户端,直到:
java.util.ConcurrentModificationException
不知道如何解决这个问题...
这是所有代码:
客户:
package main;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
public class Client {
private Socket socket = null;
private ObjectInputStream inStream = null;
private ObjectOutputStream outStream = null;
String name = "bob";
int port;
String ip;
Vector3f v3f = new Vector3f(0, 0, 0);
int clientnumber = 0;
int numberofclients = 0;
ArrayList<Vector3f> positions = new ArrayList<Vector3f>();
public Client(int port, String ip, String name) {
this.port = port;
this.ip = ip;
this.name = name;
startClient();
}
public void startClient() {
try {
socket = new Socket(ip, port);
System.out.println("Connected");
outStream = new ObjectOutputStream(socket.getOutputStream());//send name
outStream.writeObject(name);
inStream = new ObjectInputStream(socket.getInputStream());//recieve client number
clientnumber = (int) inStream.readObject();
while (true) {
v3f = new Vector3f(Math.random()*10+1, Math.random()*10+1, Math.random()*10+1);
outStream = new ObjectOutputStream(socket.getOutputStream());//send position
outStream.writeObject(v3f);
inStream = new ObjectInputStream(socket.getInputStream());//recieve position(s)
positions = (ArrayList<Vector3f>) inStream.readObject();
numberofclients = positions.size();
}
} catch (Exception e) {
System.err.println("Client Error: " + e.getMessage());
System.err.println("Localized: " + e.getLocalizedMessage());
System.err.println("Stack Trace: " + e.getStackTrace());
}
}
public static void main(String[] args) {
new Client(1500, "localHost", "bob");
}
}
服务器:
package main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Server {
static JFrame f = new JFrame();
static JPanel p = new JPanel();
static JLabel info = new JLabel();
private ServerSocket serverSocket = null;
private Socket socket = null;
private boolean connection = false;
private boolean serverisrunning = true;
private int port;
static JTextArea jt = new JTextArea();
public static boolean showtimestamp = false;
private JScrollPane sc = new JScrollPane(jt,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
String timeStamp = new SimpleDateFormat("HH:mm:ss").format(Calendar
.getInstance().getTime());
String defaulttext = System.getProperty("user.name") + " / " + getIp()
+ " > ";
String error = "Error - ";
String badcom = " Is Not Recognised As A Valid Command";
String baduse = "Incorrect Use";
String tftext = "";
ObjectInputStream inStream = null;
ObjectOutputStream outStream = null;
JTextField tf = new JTextField("/");
static ArrayList<EchoThread> clients = new ArrayList<EchoThread>();
static ArrayList<String> clientnames = new ArrayList<String>();
static ArrayList<Vector3f> clientpos = new ArrayList<Vector3f>();
Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
public Server(int port) {
this.port = port;
f.setTitle("Server");
f.setBounds(ss.width - 750, 50, 701, 350);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setAlwaysOnTop(true);
f.setLayout(null);
f.add(p);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
if (connection) {
try {
socket.close();
serverSocket.close();
} catch (IOException e) {
}
}
System.exit(0);
}
});
f.add(sc);
sc.setBounds(151, 0, 560, 300);
jt.setBackground(Color.BLACK);
jt.setForeground(Color.WHITE);
jt.setLineWrap(true);
jt.setEditable(false);
append("Hello World");
f.add(info);
info.setOpaque(true);
info.setBounds(0, 0, 150, 19);
info.setBackground(Color.RED);
info.setText("Clients Connected: " + clients.size());
f.add(tf);
tf.setBounds(151, 298, 544, 23);
tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tftext = tf.getText();
RunCommand(tftext);
tf.setText("/");
}
});
tf.setBackground(Color.BLACK);
tf.setForeground(Color.WHITE);
f.getContentPane().setBackground(Color.BLACK);
f.setVisible(true);
startServer();
}
protected void RunCommand(String txt) {
serverMessage("'" + txt.replace("/", "") + "'\n");
if (txt.contains("/")) {
if (txt.equals("/")) {
return;
}
String t = txt.toLowerCase().replace("/", "");
if (t.contains("setshowtime")) {
if (t.endsWith(" true")) {
showtimestamp = true;
append("ShowTimeStamp - true");
} else if (t.endsWith(" false")) {
showtimestamp = false;
append("ShowTimeStamp - false");
} else {
append(error + baduse + " '" + txt + "' "
+ "\nCorrect Use: SetShowTime true/false");
}
} else if (t.contains("say ")) {
message(t.replace("say ", ""));
} else if (t.contains("hello")) {
append("Hi " + System.getProperty("user.name"));
} else if (t.contains("stop")) {
serverMessage("Server Starting\nInitialising socket connections:");
serverisrunning = false;
} else if (t.contains("kick")) {
int indexOf = t.indexOf('c');
String name = t.substring(indexOf + 2).trim();
serverMessage("Kicking Player " + name);
for (int i = 0; i < clientnames.size(); i++) {
if (clientnames.get(i).toLowerCase().contains(name)) {
append("\n'" + name + "' was found: "
+ clientnames.get(i));
p.remove(clients.get(i).clientinfo);
p.revalidate();
f.validate();
f.repaint();
clients.get(i).clientinfo.setVisible(false);
clients.remove(i);
clientnames.remove(i);
info.setText("Clients Connected: " + clients.size());
}
}
} else {// if none of the other commands
append(error + "'" + t + "'" + badcom);
}
} else {
// dunno
}
}
public void sendToAll(Object message){
for(EchoThread client : clients)
client.write(clientpos.get(clients.indexOf(client)));
}
public static void removeClient(int i) {
p.remove(clients.get(i).clientinfo);
p.revalidate();
f.validate();
f.repaint();
clients.get(i).clientinfo.setVisible(false);
clients.remove(i);
clientnames.remove(i);
clientpos.remove(i);
info.setText("Clients Connected: " + clients.size());
}
public void message(String msg) {
timeStamp = new SimpleDateFormat("HH:mm-ss").format(Calendar
.getInstance().getTime());
jt.append(" [" + timeStamp + "] " + msg);
jt.append("\n" + defaulttext);
jt.setCaretPosition(jt.getDocument().getLength());
}
public void append(String text) {
timeStamp = new SimpleDateFormat("HH:mm-ss").format(Calendar
.getInstance().getTime());
if (showtimestamp) {
jt.append(" [" + timeStamp + "] ");
}
jt.append(text);
jt.append("\n" + defaulttext);
jt.setCaretPosition(jt.getDocument().getLength());
}
public static void serverMessage(String text) {
jt.append(text);
jt.setCaretPosition(jt.getDocument().getLength());
}
public void startServer() {
try {
serverSocket = new ServerSocket(port);
append("\nPort: " + port + "\nLocal IP address: "
+ InetAddress.getLocalHost().getHostAddress()
+ "\nExternal IP address: " + getIp()
+ "\nType 'stop' to stop listening for clients...\n");
while (serverisrunning) {
if (clients.size() < 15) {
socket = serverSocket.accept();
inStream = new ObjectInputStream(socket.getInputStream());// recieve username
String name = (String) inStream.readObject();
clientnames.add(name);
System.out.println(name + " Connected");
outStream = new ObjectOutputStream(socket.getOutputStream());// send client number
outStream.writeObject(clients.size() + 1);
clientpos.add(new Vector3f());
clients.add(new EchoThread(socket));
clients.get(clients.size() - 1).start();
clients.get(clients.size() - 1).clientindex = (clients
.size());
clients.get(clients.size() - 1).clientname = clientnames
.get((clients.size() - 1));
connection = true;
timeStamp = new SimpleDateFormat("HH:mm-ss")
.format(Calendar.getInstance().getTime());
append("Client Connected: " + clients.size() + "\n"
+ clients + "\n" + "Client IP: "
+ socket.getRemoteSocketAddress() + "\n\n###### "
+ name + " Connected " + timeStamp + " ######\n");
for (int i = 0; i < clients.size(); i++) {
if (!clients.get(i).isAlive()) {
clients.remove(i);
clientnames.remove(i);
}
}
}
info.setText("Clients Connected: " + clients.size());
}
} catch (Exception e) {
}
}
public static String getIp() {
URL whatismyip;
try {
whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine();
if (in != null) {
in.close();
}
return ip;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
new Server(1500);
}
}
vector 3f:
package main;
import java.io.Serializable;
import javax.swing.JTextArea;
public class Vector3f implements Serializable {
public double x;
public double y;
public double z;
public Vector3f(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector3f(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector3f(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector3f() {
this.x = 0;
this.y = 0;
this.z = 0;
}
public void OutputToConsole(String additionaltext) {
System.out.println(additionaltext + " x:" + x + " y:" + y + " z:" + z);
}
public void appendToTextArea(JTextArea ta, String additionaltext) {
ta.append(additionaltext + " x:" + x + " y:" + y + " z:" + z);
}
}
回声线程:
package main;
import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class EchoThread extends Thread {
volatile boolean finished = false;
protected Socket socket;
boolean isrunning = false;
boolean edited = false;
ObjectInputStream inStream = null;
ObjectOutputStream outStream = null;
Vector3f v3f = new Vector3f(0, 0, 0);
JLabel clientinfo = new JLabel();
JFrame f;
int clientindex = 0;
String clientname = "";
int numberofclients = Server.clients.size();
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
f = Server.f;
f.add(clientinfo);
clientinfo.setOpaque(true);
clientinfo.setBounds(0, 20 + (20 * Server.clients.size()), 150, 19);
clientinfo.setBackground(Color.GREEN);
}
public void run() {
while (!finished) {
numberofclients = Server.clients.size();
try {
inStream = new ObjectInputStream(socket.getInputStream());
v3f = (Vector3f) inStream.readObject();
clientinfo.setText("[" + clientindex + "] " + clientname + ": "
+ (int) v3f.x + "," + (int) v3f.y + "," + (int) v3f.z);
FontToFit(clientinfo);
Server.clientpos.set(clientindex-1, v3f);
outStream = new ObjectOutputStream(socket.getOutputStream());
outStream.writeObject(Server.clientpos);
} catch (Exception e) {
System.out.println(e);
try {
//Server.removeClient(clientindex - 1);
end();
Server.serverMessage(clientname + " Disconnected");
socket.shutdownOutput();
inStream.close();
outStream.close();
socket.shutdownInput();
socket.close();
} catch (IOException e1) {
}
return;
}
}
}
public void write(Object obj) {
try{
outStream.writeObject(obj);
}
catch(IOException e){ e.printStackTrace(); }
}
public void end() {
finished = true;
}
public void FontToFit(JLabel label) {
Font labelFont = label.getFont();
String labelText = label.getText();
double stringWidth = label.getFontMetrics(labelFont).stringWidth(
labelText);
double componentWidth = label.getWidth();
// Find out how much the font can grow in width.
double widthRatio = (double) componentWidth / (double) stringWidth;
double newFontSize = (int) (labelFont.getSize() * widthRatio);
double componentHeight = label.getHeight();
// Pick a new font size so it will not be larger than the height of
// label.
double fontSizeToUse = Math.min(newFontSize, componentHeight);
// Set the label's font size to the newly determined size.
label.setFont(new Font(labelFont.getName(), Font.PLAIN,
(int) fontSizeToUse - 1));
}
}
最佳答案
我没有查看您的代码示例,因为代码示例太多,但对于您在标题中提出的问题有一个简短的答案。
问:如何使用线程将一个客户端的输入广播到所有其他客户端?
答:你不知道。
每个客户端使用一个线程来接收来自每个客户端的输入,当客户端 C 向您发送某些内容时,让为客户端 C 服务的一个线程将该消息广播给所有客户端其他客户端套接字。
关于Java 套接字 - 使用线程将任何客户端输入发送到所有其他客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26278853/
我在网上搜索但没有找到任何合适的文章解释如何使用 javascript 使用 WCF 服务,尤其是 WebScriptEndpoint。 任何人都可以对此给出任何指导吗? 谢谢 最佳答案 这是一篇关于
我正在编写一个将运行 Linux 命令的 C 程序,例如: cat/etc/passwd | grep 列表 |剪切-c 1-5 我没有任何结果 *这里 parent 等待第一个 child (chi
所以我正在尝试处理文件上传,然后将该文件作为二进制文件存储到数据库中。在我存储它之后,我尝试在给定的 URL 上提供文件。我似乎找不到适合这里的方法。我需要使用数据库,因为我使用 Google 应用引
我正在尝试制作一个宏,将下面的公式添加到单元格中,然后将其拖到整个列中并在 H 列中复制相同的公式 我想在 F 和 H 列中输入公式的数据 Range("F1").formula = "=IF(ISE
问题类似于this one ,但我想使用 OperatorPrecedenceParser 解析带有函数应用程序的表达式在 FParsec . 这是我的 AST: type Expression =
我想通过使用 sequelize 和 node.js 将这个查询更改为代码取决于在哪里 select COUNT(gender) as genderCount from customers where
我正在使用GNU bash,版本5.0.3(1)-发行版(x86_64-pc-linux-gnu),我想知道为什么简单的赋值语句会出现语法错误: #/bin/bash var1=/tmp
这里,为什么我的代码在 IE 中不起作用。我的代码适用于所有浏览器。没有问题。但是当我在 IE 上运行我的项目时,它发现错误。 而且我的 jquery 类和 insertadjacentHTMl 也不
我正在尝试更改标签的innerHTML。我无权访问该表单,因此无法编辑 HTML。标签具有的唯一标识符是“for”属性。 这是输入和标签的结构:
我有一个页面,我可以在其中返回用户帖子,可以使用一些 jquery 代码对这些帖子进行即时评论,在发布新评论后,我在帖子下插入新评论以及删除 按钮。问题是 Delete 按钮在新插入的元素上不起作用,
我有一个大约有 20 列的“管道分隔”文件。我只想使用 sha1sum 散列第一列,它是一个数字,如帐号,并按原样返回其余列。 使用 awk 或 sed 执行此操作的最佳方法是什么? Accounti
我需要将以下内容插入到我的表中...我的用户表有五列 id、用户名、密码、名称、条目。 (我还没有提交任何东西到条目中,我稍后会使用 php 来做)但由于某种原因我不断收到这个错误:#1054 - U
所以我试图有一个输入字段,我可以在其中输入任何字符,但然后将输入的值小写,删除任何非字母数字字符,留下“。”而不是空格。 例如,如果我输入: 地球的 70% 是水,-!*#$^^ & 30% 土地 输
我正在尝试做一些我认为非常简单的事情,但出于某种原因我没有得到想要的结果?我是 javascript 的新手,但对 java 有经验,所以我相信我没有使用某种正确的规则。 这是一个获取输入值、检查选择
我想使用 angularjs 从 mysql 数据库加载数据。 这就是应用程序的工作原理;用户登录,他们的用户名存储在 cookie 中。该用户名显示在主页上 我想获取这个值并通过 angularjs
我正在使用 autoLayout,我想在 UITableViewCell 上放置一个 UIlabel,它应该始终位于单元格的右侧和右侧的中心。 这就是我想要实现的目标 所以在这里你可以看到我正在谈论的
我需要与 MySql 等效的 elasticsearch 查询。我的 sql 查询: SELECT DISTINCT t.product_id AS id FROM tbl_sup_price t
我正在实现代码以使用 JSON。 func setup() { if let flickrURL = NSURL(string: "https://api.flickr.com/
我尝试使用for循环声明变量,然后测试cols和rols是否相同。如果是,它将运行递归函数。但是,我在 javascript 中执行 do 时遇到问题。有人可以帮忙吗? 现在,在比较 col.1 和
我举了一个我正在处理的问题的简短示例。 HTML代码: 1 2 3 CSS 代码: .BB a:hover{ color: #000; } .BB > li:after {
我是一名优秀的程序员,十分优秀!