大家!我正在尝试使用套接字制作我的第一个 Java 应用程序。而且我无法从 Socket 读取数据。这是 ServerThread 的源代码:
public class ServerThread extends Thread{
private final int SERVER_PORT = 444;
private ServerSocket serv;
public ServerThread(){
try {
serv = new ServerSocket(SERVER_PORT);
} catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void run(){
while(true){
try {
Socket client = serv.accept();
client.setSoTimeout(0);
client.setTcpNoDelay(true);
client.setSendBufferSize(65536);
if(client.isConnected()){
new Thread(new MsgSrv(client)).start();
System.out.println("Client connected");
}
} catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
} }
这是一个处理客户端连接的类:
public class MsgSrv extends Thread{
private BufferedWriter out;
private BufferedReader in;
private boolean isFinished = false;
private String buff;
private Socket sock;
public MsgSrv(Socket sc){
try {
sock = sc;
in = new BufferedReader(new InputStreamReader(sc.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(sc.getOutputStream()));
} catch (IOException ex) {
Logger.getLogger(MsgSrv.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void run(){
while(!isFinished){
try {
buff=in.readLine();
System.out.println(buff);
out.write("Hello");
} catch (IOException ex) {
Logger.getLogger(MsgSrv.class.getName()).log(Level.SEVERE, null, ex);
isFinished=true;
}
}
}}
客户端应用程序向服务器发送一个字符串,并尝试读取答案。但什么也没有发生。in.readLine
什么都不返回,并且永远等待服务器的回答。你能帮我解决一个问题吗?
为了读取数据,我已经使用了 DataInputStream、BufferedReader 类。客户端应用程序的来源:
public class JavaApplication4 {
/**
* @param args the command line arguments
*/
public static Socket connectSock;
public static PrintWriter out;
public static DataInputStream in;
public static void main(String[] args) {
try {
connectSock = new Socket("127.0.0.1", 444);
if(connectSock.isConnected()){
in = new DataInputStream(connectSock.getInputStream());
out = new PrintWriter(connectSock.getOutputStream(), true);
out.println("!hello!");
out.flush();
String s;
while(true){
s = in.readUTF();
System.out.println(s);
}
}else
{
System.out.println("bad socket");
System.exit(0);
}
} catch (UnknownHostException ex) {
Logger.getLogger(JavaApplication4.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JavaApplication4.class.getName()).log(Level.SEVERE, null, ex);
}
}}