这个程序的目的是在客户端和服务器之间发送文本消息(字符串)(使用java线程),就像两个手机会相互发送文本消息一样。
如果命令行参数中存在“-l”,则它将运行服务器线程。如果命令行参数中不存在“-l”,那么它将运行客户端线程。
在下面的屏幕截图中,左侧窗口是服务器,右侧是客户端。
屏幕截图的问题是左窗口(服务器)应该输出“从客户端收到消息:Hello”,然后继续输出“标准输入(按完成后输入然后控制D):”
我使用“ok1,ok2,ok3,ok4”作为调试目的的标准输出(你会发现它在代码中停止了哪些行)“所以它可以在将来被删除。
有三个文件:主要功能文件,服务器文件,客户端文件。
服务器代码(DirectMessengerServer.java):
import java.io.*;
import java.net.*;
import java.util.*;
//import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerServer
{
private static Socket socket;
boolean KeepRunning = true;
void ServerRun(String[] args)
{
Thread Server = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
try
{
System.out.println("Try block begins..");
int port_number1= Integer.valueOf(args[1]);
System.out.println("Port number is: " + port_number1);
ServerSocket serverSocket = new ServerSocket(port_number1);
//SocketAddress addr = new InetSocketAddress(address, port_number1);
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + ( port_number1 ) );
while(KeepRunning)
{
System.out.println("While loop run");
//Reading the message from the client
socket = serverSocket.accept();
System.out.println("ok1");
InputStream is = socket.getInputStream();
System.out.println("ok2");
InputStreamReader isr = new InputStreamReader(is);
System.out.println("ok3");
BufferedReader br = new BufferedReader(isr);
System.out.println("ok4");
String MessageFromClient = br.readLine();
System.out.println("ok5");
System.out.println("Message received from client: "+ MessageFromClient);
//creating message to server send from standard input
String newmessage = "";
try {
// input the message from standard input
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null && KeepRunning==true )
{
newmessage += line + " \n ";
}
}
catch ( Exception e ) {
System.out.println( e.getMessage() );
}
//Writing return message back to client
String returnMessage = newmessage;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to client: "+returnMessage);
bw.flush();
//shutdown with zero-length message
if(MessageFromClient.equals("") || MessageFromClient.equals(null) || returnMessage.equals(""))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
Server.start();
}
}
客户代码(DirectMessengerClient.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerClient
{
boolean KeepRunning = true;
private static Socket socket;
//static String[] arguments;
//public static void main(String[] args)
//{
// arguments = args;
//}
public DirectMessengerClient()
{
//System.out.println("test.");
}
public void ClientRun(String[] args)
{
Thread Client = new Thread ()
{
public void run()
{
System.out.println("Client thread is now running");
try
{
System.out.println("Try block begins..");
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + port_number1 );
while(KeepRunning)
{
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null )
{
newmessage += line + " ";
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String messageFromServer = br.readLine();
System.out.println("Message received from server: " + messageFromServer);
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
Client.start();
}
}
主要代码(DirectMessengerCombined.java):
public class DirectMessengerCombined
{
public static void main(String[] args)
{
DirectMessengerClient Client1 = new DirectMessengerClient();
DirectMessengerServer Server1 = new DirectMessengerServer();
for (int i = 0; i < args.length; i++)
{
if(!args[0].equals("-l"))
{
Client1.ClientRun(args);
}
switch (args[0].charAt(0))
{
case '-':
if(args[0].equals("-l"))
{
Server1.ServerRun(args);
}
}
i=args.length + 20;
}
}
}
我的问题是:为什么程序在输出ok4的行(服务器窗口)停止运行?没有错误消息,所以我也想知道如果我以某种方式错过它,如何找到错误消息?
答案 0 :(得分:0)
在DirectMessengerClient
课程中,您永远不会将消息发送到服务器。在代码中添加一行来执行此操作:
String sendMessage = newmessage;
bw.write(sendMessage + "\n"); // <--- ADD THIS LINE
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
另请注意,在服务器类中,您正在发送返回消息。但是对BufferedWriter.write
的调用不会在消息末尾添加换行符(与System.out.println
不同),因此如果您希望能够使用{{1}读取行,则需要自己添加换行符。 }}:
BufferedReader.readLine