我正在尝试使用 java 程序读取数据并将其写入服务器。我正在使用控制台写入数据。我可以成功地将数据写入服务器,但是当我尝试读取服务器发送的数据时,问题就来了。
import java.io.*;
import java.net.*;
public class EMSSocketConnection {
public static void main(String[] args) throws Exception {
createSocket();
}
private static void sendMessage(DataOutputStream out) throws Exception
{
try
{
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userOutput;
while ((userOutput = stdIn.readLine()) != null)
{
out.writeBytes(userOutput);
out.write('\n');
}
out.flush();
}
catch(Exception ex)
{
System.out.println(ex.getStackTrace());
}
finally
{
out.close();
}
}
private static void readResponse(DataInputStream in) throws Exception
{
try
{
byte[] data = new byte[1024];
in.readFully(data);
System.out.println(data);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
finally
{
in.close();
}
}
private static void createSocket()
{
try
{
int port = 2345;
InetAddress address = InetAddress.getByName("192.100.100.129");
final Socket client = new Socket(address, port);
final DataOutputStream out = new DataOutputStream(client.getOutputStream());
final DataInputStream in = new DataInputStream(client.getInputStream());
System.out.println("Successfully Connected");
new Thread() {
public void run() {
synchronized(client)
{
try {
while(true)
{
sendMessage(out);
readResponse(in);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
}.start();
}
catch(Exception ex)
{
ex.getStackTrace();
}
}
}
谁能告诉我如何成功地从服务器读取数据?