這是我第一次製作TCP客戶機/服務器程序。我應該製作一個簡單的Java客戶端和服務器程序,要求客戶端提供用戶名和密碼。從那裏服務器檢查其用戶數據庫(我嘗試使用覆蓋維數組創建)來查看是否存在匹配,並向客戶端返回一條消息,指出「Hello」(用戶名),然後告訴用戶所有其他用戶服務器上的註冊用戶。Java TCP客戶機/服務器和環路問題
我特定問題然而,就是每當我跑了兩下,當我在部分到達了服務器應該經過循環,全部顯示爲「目前在服務器上註冊的其他用戶包括:MATTCARLJOHN目前在服務器上註冊的其他用戶包括:MATTCARLJOHN目前在服務器上註冊的其他用戶包括:MATTCARLJOHN「。
似乎我的服務器完全忽略了我的for循環,並且如果語句應該檢查身份驗證並直接跳到該循環,而不管我在客戶端輸入了我的用戶名和密碼。
這裏有兩個方案: 客戶
import java.io.*;
import java.net.*;
class TCPClient2
{
public static void main(String argv[]) throws Exception
{
String userName;
String passWord;
String loginInfo;
String loginInfo2;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Username: ");
userName = inFromUser.readLine();
outToServer.writeBytes(userName + '\n');
System.out.println("Password: ");
passWord = inFromUser.readLine();
outToServer.writeBytes(passWord + '\n');
loginInfo = inFromServer.readLine();
System.out.println(loginInfo);
clientSocket.close();
}
}
和服務器
import java.io.*;
import java.net.*;
class TCPServer2
{
public static void main(String argv[]) throws Exception
{
ServerSocket welcomeSocket = new ServerSocket(6789);
String[][] Login = {{"MATT","UNCP"},{"JOHN","UNCP"},{"CARL","UNCP"}};
String username;
String username1;
String password;
String password1;
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
username = inFromClient.readLine();
System.out.println("Username received: " + username);
password = inFromClient.readLine();
System.out.println("Password received: " + password);
username1=username.toUpperCase() + '\n';
password1=password.toUpperCase() + '\n';
for(int i = 0; i<Login.length; i++){
if(Login[i][0].equals(username1) && Login[i][1].equals(password1)){
outToClient.writeBytes("Hello " + username1);
outToClient.writeBytes("Other users registered on the server currently include: ");
for(int k = 0; k<Login.length; k++){
outToClient.writeBytes(Login[k][0]);}
else
outToClient.writeBytes("Invalid Username and/or password.");
}
}
}
}
}
任何幫助將非常可以理解的,這是在網站上我第一次發佈我對網絡和Java一般都很陌生,所以請原諒我,如果我的問題看起來很混亂。
謝謝。
嚴,這是所有對我也有效,這是大的for循環低於它,雖然這是我的但主要問題,並得到它認識到成功的用戶登錄。 – user1373440