您好,我是 Java 套接字编程的新手,我只是想看看是否有人可以给我一些帮助。
我将发布客户端和服务器的代码,然后我将解释我的问题......
reader = new BufferedReader(new InputStreamReader(socket.getInputStream));
while(running)
{
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
stream = new PrintStream(socket.getOutputStream());
stream.println("return: " + line);
}
}
}catch(IOException e)
{
System.out.println("Socket in use or not available: " + port);
}
}
public static void main()
{
run();
}
//Client
public static String ip;
public static int port;
public static Socket socket;
public static PrintStream stream;
public static BufferedReader reader;
public static void main(String args[])
{
try
{
socket = new socket(ip, port);
stream = new PrintStream(socket.getOutputStream());
stream.println("test0");
reader = new BufferedReader(new InputStreamReader(socket.getInputStream));
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
}
stream.println("test1");
line = reader.readLine();
if(line != null)
{
System.out.println(line);
}
}catch(IOException e)
{
System.out.println("could not connect to server!");
}
}
所以我的问题是,即使我摆脱了循环并尝试让它发送两次字符串,它也不会发送它。除非我关闭并在客户端创建一个新套接字,否则它只会执行一次。因此,如果有人能给我解释我做错了什么,那就太好了,非常感谢。