我一直在尝试创建一个相当基本的客户端/服务器,以通过Java中的套接字通信对象。我是一名学生/业余程序员,所以我可能只是想念一些东西。我之前已经成功地使客户机/服务器通过套接字进行通信,但是没有通过对象进行通信,所以我的代码是新的。当我启动服务器时,它会等待连接。然后,我启动我的客户端,并且它连接了(服务器在其屏幕上确认了这一点)。然后,当客户端从用户那里获取密码时,它要么发送密码,服务器就无法对其进行处理,否则它将无法正确发送密码。它确实在.write()之后到达了.println(“ Message send”),所以我认为问题在于服务器正在读取它。也许等待ObjectInputStream读取数据的while循环以某种方式跳过了什么时候有东西呢?我不确定我是否真的可以使用一些帮助。
客户代码:
Socket socket = new Socket(“ 192.168.50.18”,8295);扫描仪控制台=新的Scanner(System.in);
Integer rand = getRandom(9);
OutputStream outStream = socket.getOutputStream();
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Out streams initialized.");
InputStream inStream = socket.getInputStream();
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
System.out.print("In streams initialized.");
System.out.println("IO streams fully generated.");
boolean waiting = true;
/**
while(waiting){
if(inStream.readNBytes(1)!=null){
waiting=false;
}
}
System.out.println("Pinged server successfully;");
**/
System.out.println("Enter password: ");
String passGuess = console.next();
System.out.println("Rand = "+rand);
String message = getSHA(passGuess+rand.toString())+rand;
System.out.println("Message: "+message);
outStream.write(message.getBytes());
//output.writeObject(message);
System.out.println("Sent "+message);
outStream.flush();
waiting = true;
while(waiting){
try {
if (in.readUTF()!=null&&in.readLine().equals("1")) {
System.out.println("Authentication successful.");
waiting = false;
}
}catch(EOFException e){
e.printStackTrace();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
服务器代码:
try{
server = new ServerSocket(port);
System.out.println(server.getInetAddress());
while(true){
System.out.println("Waiting for connection request");
Socket socket = server.accept();
System.out.println("Connection request received;,");
/**
out.write(1);
out.flush();
System.out.println("Sent client ping,");
**/
InputStream intake = socket.getInputStream();
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
String received = null;
intake.wait();
while(received==null){
try {
received = intake.readAllBytes().toString();
}catch(Exception e){
}
}
System.out.println("Authenticating...");
if(authenticate(received)){
System.out.println("Client authenticated");
out.write(1);//lets the client know they are authenticated.
start(socket,socket.getInputStream(),out);
} else {
System.out.println("Client failed to authenticate, disconnecting.");
socket.close();
}
}
}catch(Exception e){
e.printStackTrace();
}
我几个月前尝试过相同的方法,但我记不起很多。我有我正在从事的大学项目,我将其上传到github,希望您能找到有用的东西。https://github.com/MohamedWSalah/Java-Socket-Programming-News-App