- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前正在制作一个消息传递应用程序,稍后我还将为其添加加密。我有一台打开套接字并等待客户端连接的服务器。客户端连接后,它会为该客户端创建一个新线程。然后等待消息等。
我遇到的问题是,当我尝试将公钥指数和模数发送给客户端时,客户端无法使用 datainputstream(clientSocket.getInputStream()).readLine
.
指数和模数的发送发生在 line 173 and 174
.客户端的接收发生在125 and 136
线上.
服务器发送数据。
os.println(modulusMap.get(requestName));
os.println(exponentMap.get(requestName));
客户端试图将数据写入变量:
pubModulusString = is.readLine().trim();<br/>
BigInteger pubModulus = new BigInteger(pubModulusString);<br/>
HashMap<String, BigInteger> modulusMap = new HashMap<String, BigInteger>();
modulusMap.put(message.substring(1), pubModulus);<br/>
String pubExponentString = is.readLine();
我已经测试了将数据发送作为打印流进行测试,它运行良好。只有当我尝试读取数据并将其保存到变量时才会出现问题 (line 125 and 136)
.
大部分时间 readLine()
读取模数只是空白,但有时它会成功读取它。我找不到成功与否的模式。
同样很奇怪的是,我使用完全相同的代码将数据从客户端发送到服务器。这可以在客户端看到 line 89 and 91
.服务器收到 lines 113 and 119
上的数据.
感谢您提前提供任何帮助或想法。
下面发布的是任何 1 的完整代码,它足够好并且有时间运行它。
服务器:
import java.io.*;
import java.math.*;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.*;
/*
* A chat server that delivers public and private messages.
*/
public class MultiThreadChatServerSync {
// The server socket.
private static ServerSocket serverSocket = null;
// The client socket.
private static Socket clientSocket = null;
// This chat server can accept up to maxClientsCount clients' connections.
private static final int maxClientsCount = 10;
private static final clientThread[] threads = new clientThread[maxClientsCount];
public static void main(String args[]) {
// The default port number.
int portNumber = 2222;
if (args.length < 1) {
System.out.println("Usage: java MultiThreadChatServerSync <portNumber>\n"
+ "Now using port number=" + portNumber);
} else {
portNumber = Integer.valueOf(args[0]).intValue();
}
/*
* Open a server socket on the portNumber (default 2222). Note that we can
* not choose a port less than 1023 if we are not privileged users (root).
*/
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
System.out.println(e);
}
/*
* Create a client socket for each connection and pass it to a new client
* thread.
*/
while (true) {
try {
clientSocket = serverSocket.accept();
int i = 0;
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] == null) {
(threads[i] = new clientThread(clientSocket, threads)).start();
break;
}
}
if (i == maxClientsCount) {
PrintStream os = new PrintStream(clientSocket.getOutputStream());
os.println("Server too busy. Try later.");
os.close();
clientSocket.close();
}
} catch (IOException e) {
System.out.println(e);
}
}
}
}
/*
* The chat client thread. This client thread opens the input and the output
* streams for a particular client, ask the client's name, informs all the
* clients connected to the server about the fact that a new client has joined
* the chat room, and as long as it receive data, echos that data back to all
* other clients. The thread broadcast the incoming messages to all clients and
* routes the private message to the particular client. When a client leaves the
* chat room this thread informs also all the clients about that and terminates.
*/
class clientThread extends Thread {
private String clientName = null;
private DataInputStream is = null;
private BufferedReader inputLine = null;
private PrintStream os = null;
private Socket clientSocket = null;
private final clientThread[] threads;
private int maxClientsCount;
public clientThread(Socket clientSocket, clientThread[] threads) {
this.clientSocket = clientSocket;
this.threads = threads;
maxClientsCount = threads.length;
}
public void run() {
int maxClientsCount = this.maxClientsCount;
clientThread[] threads = this.threads;
HashMap<String, BigInteger> modulusMap = new HashMap<String, BigInteger>();
HashMap<String, BigInteger> exponentMap = new HashMap<String, BigInteger>();
try {
/*
* Create input and output streams for this client.
*/
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
inputLine = new BufferedReader (new InputStreamReader(System.in));
String name;
while (true) {
os.println("Enter your name.");
name = is.readLine().trim();
String pubModulusString = is.readLine().trim();
BigInteger pubModulus = new BigInteger(pubModulusString);
modulusMap.put(name, pubModulus);
String pubExponentString = is.readLine().trim();
BigInteger pubExponent = new BigInteger(pubExponentString);
exponentMap.put(name, pubExponent);
if (name.indexOf('@') == -1) {
break;
} else {
os.println("The name should not contain '@' character.");
}
}
/* Welcome the new the client. */
os.println("Welcome " + name
+ " to our chat room.\nTo leave enter /quit in a new line.");
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] == this) {
clientName = "@" + name;
break;
}
}
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] != this) {
threads[i].os.println("*** A new user " + name
+ " entered the chat room !!! ***");
}
}
}
/* Start the conversation. */
while (true) {
String line = is.readLine();
if (line.startsWith("/quit")) {
break;
}
if (line.startsWith("!")){
String requestName;
requestName = line;
requestName = requestName.substring(1);
os.println(modulusMap.get(requestName));
os.println(exponentMap.get(requestName));
}
else {
/* If the message is private sent it to the given client. */
if (line.startsWith("@")) {
String[] words = line.split("\\s", 2);
if (words.length > 1 && words[1] != null) {
words[1] = words[1].trim();
if (!words[1].isEmpty()) {
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] != this
&& threads[i].clientName != null
&& threads[i].clientName.equals(words[0])) {
threads[i].os.println("<" + name + "> " + words[1]);
/*
* Echo this message to let the client know the private
* message was sent.
*/
this.os.println(">" + name + "> " + words[1]);
break;
}
}
}
}
}
} else {
/* The message is public, broadcast it to all other clients. */
synchronized (this) {
this.os.println("Please select who you wish to message by typing '@username *Your Message*'");
}
}
}
}
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] != this
&& threads[i].clientName != null) {
threads[i].os.println("*** The user " + name
+ " is leaving the chat room !!! ***");
}
}
}
os.println("*** Bye " + name + " ***");
/*
* Clean up. Set the current thread variable to null so that a new client
* could be accepted by the server.
*/
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] == this) {
threads[i] = null;
}
}
}
/*
* Close the output stream, close the input stream, close the socket.
*/
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
}
}
}
客户端
import java.io.DataInputStream;
import java.io.*;
import java.math.*;
import java.math.BigInteger;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.security.*;
import java.security.spec.*;
import java.util.*;
import javax.crypto.*;
public class MultiThreadChatClient implements Runnable {
// The client socket
private static Socket clientSocket = null;
// The output stream
private static PrintStream os = null;
// The input stream
private static DataInputStream is = null;
private static BufferedReader inputLine = null;
private static boolean closed = false;
private static final String PUBLIC_KEY_FILE = "Public.key";
private static final String PRIVATE_KEY_FILE = "Private.key";
public static void main(String[] args) {
// The default port.
int portNumber = 2222;
// The default host.
String host = "192.168.0.16";
if (args.length < 2) {
System.out
.println("Usage: java MultiThreadChatClient <host> <portNumber>\n"
+ "Now using host=" + host + ", portNumber=" + portNumber);
} else {
host = args[0];
portNumber = Integer.valueOf(args[1]).intValue();
}
/*
* Open a socket on a given host and port. Open input and output streams.
*/
try {
clientSocket = new Socket(host, portNumber);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + host);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the host "
+ host);
}
/*
* If everything has been initialized then we want to write some data to the
* socket we have opened a connection to on the port portNumber.
*/
if (clientSocket != null && os != null && is != null) {
try {
/* Create a thread to read from the server. */
new Thread(new MultiThreadChatClient()).start();
String myName = inputLine.readLine();
os.println(myName.trim());
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); //1024 used for normal securities
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
//Pullingout parameters which makes up Key
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec rsaPubKeySpec = (RSAPublicKeySpec) keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
RSAPrivateKeySpec rsaPrivKeySpec = (RSAPrivateKeySpec) keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);
os.println(rsaPubKeySpec.getModulus());
System.out.println(rsaPubKeySpec.getModulus());
os.println(rsaPubKeySpec.getPublicExponent());
FileOutputStream fos = null;
ObjectOutputStream oos = null;
fos = new FileOutputStream(PUBLIC_KEY_FILE);
oos = new ObjectOutputStream(new BufferedOutputStream(fos));
oos.writeObject(rsaPubKeySpec.getModulus());
oos.writeObject(rsaPubKeySpec.getPublicExponent());
oos.close();
fos.close();
fos = new FileOutputStream(PRIVATE_KEY_FILE);
oos = new ObjectOutputStream(new BufferedOutputStream(fos));
oos.writeObject(rsaPrivKeySpec.getModulus());
oos.writeObject(rsaPrivKeySpec.getPrivateExponent());
oos.close();
fos.close();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (InvalidKeySpecException e) {
e.printStackTrace();
}
while (!closed) {
String message = inputLine.readLine();
if (message.startsWith("!")){
os.println(message.trim());
String pubModulusString = is.readLine().trim();
BigInteger pubModulus = new BigInteger(pubModulusString);
HashMap<String, BigInteger> modulusMap = new HashMap<String, BigInteger>();
modulusMap.put(message.substring(1), pubModulus);
String pubExponentString = is.readLine();
BigInteger pubExponent = new BigInteger(pubExponentString);
HashMap<String, BigInteger> exponentMap = new HashMap<String, BigInteger>();
exponentMap.put(message.substring(1), pubExponent);
System.out.println(modulusMap.get(message.substring(1)) + " Hi");
System.out.println(exponentMap.get(message.substring(1)) + "asdk");
}
else{
// INSERT ENCRYPTION ON "message" here
os.println(message.trim());
}
}
/*
* Close the output stream, close the input stream, close the socket.
*/
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
/*
* Create a thread to read from the server. (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
public void run() {
/*
* Keep on reading from the socket till we receive "Bye" from the
* server. Once we received that then we want to break.
*/
String responseLine;
try {
while ((responseLine = is.readLine()) != null) {
System.out.println(responseLine);
if (responseLine.indexOf("*** Bye") != -1)
break;
}
closed = true;
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
最佳答案
如果 readLine() 返回一个空行,那是因为发送者发送了一个空行。如果返回 null,则发送方已关闭连接。
你找错地方了。
关于Java DataInputStream 有时返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23870164/
按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
在编码时,我问了自己这个问题: 这样更快吗: if(false) return true; else return false; 比这个? if(false) return true; return
如何在逻辑条件下进行“返回”? 在这样的情况下这会很有用 checkConfig() || return false; var iNeedThis=doSomething() || return fa
这是我的正则表达式 demo 如问题所述: 如果第一个数字是 1 则返回 1 但如果是 145 则返回 145 但如果是 133 则返回 133 样本数据a: K'8134567 K'81345678
在代码高尔夫问答部分查看谜题和答案时,我遇到了 this solution返回 1 的最长和最晦涩的方法 引用答案, int foo(void) { return! 0; } int bar(
我想在下面返回 JSON。 { "name": "jackie" } postman 给我错误。说明 Unexpected 'n' 这里是 Spring Boot 的新手。 1日龄。有没有正确的方法来
只要“is”返回 True,“==”不应该返回 True 吗? In [101]: np.NAN is np.nan is np.NaN Out[101]: True In [102]: np.NAN
我需要获取所有在 6 号或 7 号房间或根本不在任何房间的学生的详细信息。如果他们在其他房间,简单地说,我不希望有那个记录。 我的架构是: students(roll_no, name,class,.
我有一个表单,我将它发送到 php 以通过 ajax 插入到 mysql 数据库中。一切顺利,php 返回 "true" 值,但在 ajax 中它显示 false 消息。 在这里你可以查看php代码:
我在 Kotlin 中遇到了一个非常奇怪的无法解释的值比较问题,以下代码打印 假 data class Foo ( val a: Byte ) fun main() { val NUM
请注意,这并非特定于 Protractor。问题在于 Angular 2 的内置 Testability service Protractor 碰巧使用。 Protractor 调用 Testabil
在调试窗口中,以下表达式均返回 1。 Application.WorksheetFunction.CountA(Cells(4 + (i - 1) * rows_per_record, 28) & "
我在本地使用 jsonplaceholder ( http://jsonplaceholder.typicode.com/)。我正在通过 extjs rest 代理测试我的 GET 和 POST 调用
这是 Postman 为成功调用我的页面而提供的(修改后的)代码段。 var client = new RestClient("http://sub.example.com/wp-json/wp/v2
这个问题在这里已经有了答案: What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must
我想我对 C 命令行参数有点生疏。我查看了我的一些旧代码,但无论这个版本是什么,都会出现段错误。 运行方式是 ./foo -n num(其中 num 是用户在命令行中输入的数字) 但不知何故它不起作用
我已经编写了一个类来处理命名管道连接,如果我创建了一个实例,关闭它,然后尝试创建另一个实例,调用 CreateFile() 返回 INVALID_HANDLE_VALUE,并且 GetLastErro
即使 is_writable() 返回 true,我也无法写入文件。当然,该文件存在并且显然是可读的。这是代码: $file = "data"; echo file_get_contents($fil
下面代码中的变量 $response 为 NULL,尽管它应该是 SOAP 请求的值。 (潮汐列表)。当我调用 $client->__getLastResponse() 时,我从 SOAP 服务获得了
我一直在网上的不同论坛上搜索答案,但似乎没有与我的情况相符的... 我正在使用 Windows 7,VS2010。 我有一个使用定时器来调用任务栏刷新功能的应用程序。在该任务栏函数中包含对 LoadI
我是一名优秀的程序员,十分优秀!