我的Socket没有将消息发送到服务器或返回客户端...,IDK为什么,但我可以连接到服务器....
我试图解决这个问题,但我不能,每一种可能的方式对我都不起作用。 所以我希望这里的一些人可以帮助我。
感谢您阅读..,这是服务器:
package test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
import ADG.luxemita.LuxEmita;
public class serverHostTest{
static Socket socket;
static DataInputStream in;
static ServerSocket serverSocket;
//static InputStreamReader isr;
static BufferedReader br;
//static BufferedReader stdBr;
//static InputStream is;
static DataOutputStream out;
//static OutputStreamWriter osw;
static BufferedWriter bw;
//static OutputStream os;
static PrintWriter stdOut;
public serverHostTest(String[] args) throws Exception{
int port = Integer.parseInt(args[2]);
LuxEmita.luxLogger.logInfo("Starting Server....");
serverSocket = new ServerSocket(port);
LuxEmita.luxLogger.logInfo("Started Server....");
socket = serverSocket.accept();
LuxEmita.luxLogger.logInfo("Intialized Socket....");
out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("Server Started Successfully!, Some more data...");
//SetupEvent.initInstance();
/*out = new DataOutputStream(socket.getOutputStream());
os = socket.getOutputStream();
osw = new OutputStreamWriter(os);
bw = new BufferedWriter(osw);
stdOut = new PrintWriter(socket.getOutputStream(), true);
in = new DataInputStream(socket.getInputStream());
is = socket.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
stdBr = new BufferedReader(new InputStreamReader(System.in));
in2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));*/
stdOut = new PrintWriter(socket.getOutputStream(), true);
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(serverHostTest.serverSocket != null && socket != null){
new Timer().schedule(new TimerTask() {
public void run(){
try {
if(br.readLine() != null){
String test = br.readLine();
System.out.println("Received MSG: " + test);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}, 1, 1);
}
}
public static void say(String[] args) throws Exception {
stdOut.write(args[2]);
stdOut.flush();
System.out.println("Message sent to the client is " + args[2]);
}
}
答案 0 :(得分:2)
也许您的问题与以下内容有关:
try {
if(br.readLine() != null){
String test = br.readLine();
System.out.println("Received MSG: " + test);
}
} catch (IOException e) {
e.printStackTrace();
}
注意你是如何阅读两次的。将第一个br.readLine()
存储在String
变量中,然后使用该变量而不是再次读取。