- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试访问我的列表中的数据,但它总是以 null 或其中没有任何内容结束。我运行我的 Class Server
那有 public static ArrayList<String> clientUsernameList = new ArrayList<>();
在代码中。如果我的服务器接受套接字,则应该出现以下代码。
package multi.threaded_server_application;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.Clock;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import jdk.nashorn.internal.codegen.CompilerConstants;
/**
*
* @author Seeya
*/
public class Server {
public static ArrayList<String> clientUsernameList = new ArrayList<>();
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
int port = 8900; //Port number the ServerSocket is going to use
ServerSocket myServerSocket = null; //Serversocket for sockets to connect
Socket clientSocket = null; //Listerner for accepted clients
ClientThread[] clientsConnected = new ClientThread[20]; //Max clients in this server
DataInputStream IN = null;
try {
myServerSocket = new ServerSocket(port);
System.out.println("Server waiting for clients on port:" + port);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
while (true) {
try { //Freezes while-loop untill a socket have been accepted or if some failure occur
clientSocket = myServerSocket.accept();
IN = new DataInputStream(clientSocket.getInputStream());
String userName = IN.readUTF();
Server.clientUsernameList.add(userName);
System.out.println("Client have connected from:" + clientSocket.getLocalAddress().getHostName());
System.out.println("Username:" + userName);
System.out.println(Server.clientUsernameList);
} catch (Exception e) {
//Print out exception
System.out.println(e);
}
//For-loop that counts every element in Array-clientsConnected
for (int i = 0; i < clientsConnected.length; i++) {
//If-statement checks if current element is null
if(clientsConnected[i] == null){
//If current element in the Array is null then create a new object from ClientThread class
//With a socket and the object of itself as parameter.
(clientsConnected[i] = new ClientThread(clientSocket, clientsConnected)).start();
//Must have a break otherwise it will create 20 objects (Exit for-loop)
break;
} //Exit if-statement
} //Exit for-loop
} //Exit while-loop
}
} 我从我的 Class Client
收到用户名当它运行时。我把它打印出来,看看我是否在列表中添加了用户名。现在,当我尝试从我的 Class Client
访问数据时我什么也没收到/null。
package Server_application;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Seeya
*/
public class Client extends Thread {
ClientGUI GUI = null;
DataInputStream IN = null;
DataOutputStream OUT = null;
Socket SOCKET = null;
String Message = null;
String userName = null;
String ipAdress = "localhost";
int port = 8900;
public Client(ClientGUI gui,String username) {
this.userName = username;
this.GUI = gui;
}
@Override
public void run() {
try {
//Handle Input/Output from client
SOCKET = new Socket(ipAdress, port);
IN = new DataInputStream(SOCKET.getInputStream());
OUT = new DataOutputStream(SOCKET.getOutputStream());
//Sends username to server!
OUT.writeUTF(userName);
System.out.println(Server.clientUsernameList);
GUI.addToList(Server.clientUsernameList.toString());
while (true) {
CheckForMessages(IN);
}
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
//-----------------------------------------------------------------
//Method for sending Messages!
public void write(String s) throws IOException{
//Writes message to server so it can send it to other clients.
//Also sends to clients self GUI
String A = s;
OUT.writeUTF(A);
GUI.writeGUI("You said: " + A);
}
//------------------------------------------------------------------
//Method for listening on messages
private void CheckForMessages(DataInputStream in) throws IOException {
try {
String IncomingMessage = in.readUTF();
System.out.println(IncomingMessage);
GUI.writeGUI(IncomingMessage);
} catch (Exception e) {
System.err.println(e);
}
}
}
打印出来的都是[]
来 self 的 Class Client
.我尝试访问静态变量的方式有问题吗?
编辑!这是我用来向服务器中的所有客户端发送/接收消息的代码。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package multi.threaded_server_application;
import com.sun.security.ntlm.Client;
import java.awt.List;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
/**
*
* @author Seeya
*/
//THIS CLASS TAKES CARE OF HANDLING MESSAGES TO OTHER CLIENTS!
//-------------------------------------------------------
public class ClientThread extends Thread {
private ClientThread[] clientsConnected;
private Socket SOCKET = null;
private DataInputStream IN = null;
private DataOutputStream OUT = null;
private String userName = null;
//-------------------------------------------------------
//Constructor
public ClientThread(Socket socket, ClientThread[] clientThread) {
this.SOCKET = socket;
this.clientsConnected = clientThread;
}
//This starts as soon as the constructor is done/been created.
@Override
public void run() {
try {
//Handleing the messages
IN = new DataInputStream(SOCKET.getInputStream());
OUT = new DataOutputStream(SOCKET.getOutputStream());
String message = null;
while (true) {
//This will be read second from the socket DataOutPutStream
//We will use this string to send a message to every client that is online
message = IN.readUTF();
//For-loop to check how many people are actually online
//for (ClientThread k : clientsConnected) = For each client in clientsConnected ends up in variable k
for (int i = 0; i < clientsConnected.length; i++) {
//don't send message to yourself
if (clientsConnected[i]!= null && clientsConnected[i].userName != this.userName){
// loops through all the list and calls the objects sendMessage method.
clientsConnected[i].sendMessage(message, userName);
}
}
}
} catch (IOException ex) {
Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void sendMessage(String message, String userName) {
try {
Date date = new Date();
DateFormat format = new SimpleDateFormat("HH:mm:ss");
OUT.writeUTF(format.format(date) + " " + userName + " says: " + message);
OUT.flush();
} catch (IOException ex) {
Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Something failed to send message");
}
}
}
最佳答案
如果您希望从服务器字符串中获取客户端用户名 static
关闭它,您将需要通过使用循环创建的套接字向客户端发送用户名,客户端将需要代码来读取用户名列表。
我不知道这是否会神奇地让您的程序执行您想要的操作,但这些代码足以让您理解我认为的概念。
在您的服务器类中
while (true) {
try { //Freezes while-loop until a socket have been accepted or if some failure occur
clientSocket = myServerSocket.accept();
IN = new DataInputStream(clientSocket.getInputStream());
String userName = IN.readUTF();
OnConnect(userName); // Where to call the below method.
System.out.println("Client have connected from:" + clientSocket.getLocalAddress().getHostName());
System.out.println("Username:" + userName);
System.out.println(Server.clientUsernameList);
} catch (Exception e) {
//Print out exception
System.out.println(e);
}
//.... More of your code.
String userNamesCSVs = ""
private void OnConnect(String theNewConnectionName){
//For-Each loop says for every ClientThread object in clientsConnected do this block of code
for(ClientThread client : clientsConnected){
//Construct a long string with comma's in it.
userNamesCSVs = userNamesCSVs + client.userName + ",";
}
//Don't forget to count the new name! This was added so you didn't have to do
//tricky stuff in the above for loop with the trailing comma. Also the server
//doesn't have your user name yet.
userNamesCSVs = userNamesCSVs + theNewConnectionName;
//New for loop to start sending a mass message. Same as before.
for(ClientThread client : clientsConnected){
client.sendMessage(userNamesCSVs, userName);
}
//Remember take that static off clientUsernameList. Look up static it's not what you want here.
clientUsernameList.add(userName);
}
在您从服务器接收消息的客户端类中。
String[] userNameArray = new String[20]; //Max users and what not.
//Same method you are using named check for messages. It's needed to get the data from the server.
private void getUserNames(DataInputStream in) throws IOException{
try {
String userNames = in.readUTF();
System.out.println(IncomingMessage);
userNameArray = userNames.split(",")
} catch (Exception e) {
System.err.println(e);
}
for(String user : userNames){
GUI.writeGuid("User connected: " + user);
}
}
旁注:
要查找的另一件事是 'serializable'和字节流和其他类似的很酷的东西。一旦您掌握了通过客户端和服务器来回发送字符串,这就很容易做到。基本上您可以发送整个对象,而不仅仅是字符串,只要它是可序列化的即可。
关于java - 为什么我不能访问我的静态列表中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28638308/
关闭。这个问题是opinion-based 。目前不接受答案。 想要改进这个问题吗?更新问题,以便 editing this post 可以用事实和引文来回答它。 . 已关闭 4 年前。 Improv
PowerShell Web Access 允许您通过 Web 浏览器运行 PowerShell cmdlet。它显示了一个基于 Web 的控制台窗口。 有没有办法运行 cmdlet 而无需在控制台窗
我尝试在无需用户登录的情况下访问 Sharepoint 文件。 我可以通过以下任一方式获取访问 token 方法一: var client = new RestClient("https://logi
我目前正在尝试通过 Chrome 扩展程序访问 Google 服务。我的理解是,对于 JS 应用程序,Google 首选的身份验证机制是 OAuth。我的应用目前已成功通过 OAuth 向服务进行身份
假设我有纯抽象类 IHandler 和派生自它的类: class IHandler { public: virtual int process_input(char input) = 0; };
我有一个带有 ThymeLeaf 和 Dojo 的 Spring 应用程序,这给我带来了问题。当我从我的 HTML 文件中引用 CSS 文件时,它们在 Firebug 中显示为中止。但是,当我通过在地
这个问题已经有答案了: JavaScript property access: dot notation vs. brackets? (17 个回答) 已关闭 6 年前。 为什么这不起作用? func
我想将所有流量重定向到 https,只有 robot.txt 应该可以通过 http 访问。 是否可以为 robot.txt 文件创建异常(exception)? 我的 .htaccess 文件: R
我遇到了 LinkedIn OAuth2: "Unable to verify access token" 中描述的相同问题;但是,那里描述的解决方案并不能解决我的问题。 我能够成功请求访问 toke
问题 我有一个暴露给 *:8080 的 Docker 服务容器. 我无法通过 localhost:8080 访问容器. Chrome /curl无限期挂断。 但是如果我使用任何其他本地IP,我就可以访
我正在使用 Google 的 Oauth 2.0 来获取用户的 access_token,但我不知道如何将它与 imaplib 一起使用来访问收件箱。 最佳答案 下面是带有 oauth 2.0 的 I
我正在做 docker 入门指南:https://docs.docker.com/get-started/part3/#recap-and-cheat-sheet-optional docker-co
我正在尝试使用静态 IP 在 AKS 上创建一个 Web 应用程序,自然找到了一个带有 Nginx ingress controller in Azure's documentation 的解决方案。
这是我在名为 foo.js 的文件中的代码。 console.log('module.exports:', module.exports) console.log('module.id:', modu
我试图理解访问键。我读过https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-se
我正在使用 MGTwitterEngine"将 twitter 集成到我的应用程序中。它在 iOS 4.2 上运行良好。当我尝试从任何 iOS 5 设备访问 twitter 时,我遇到了身份验证 to
我试图理解访问键。我读过https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-se
我正在使用以下 API 列出我的 Facebook 好友。 https://graph.facebook.com/me/friends?access_token= ??? 我想知道访问 token 过
401 Unauthorized - Show headers - { "error": { "errors": [ { "domain": "global", "reas
我已经将我的 django 应用程序部署到 heroku 并使用 Amazon s3 存储桶存储静态文件,我发现从 s3 存储桶到 heroku 获取数据没有问题。但是,当我测试查看内容存储位置时,除
我是一名优秀的程序员,十分优秀!