java socket通信中,编写的客户端代码第二次发送消息时服务器端收不到
各位大侠,帮忙看一下,今天没事写了一个简单的socket小应用,客户端和服务器端的会话,当程序运行时,客户端先输入信息后回车,这时Eclipse的控制台由客户端的转化成服务器端的控制台,服务器端收到客户端的信息后进行答复,控制台自然而然的又转化成客户端的控制台,并显示之前客户端和服务器端的第一次回话内容,但是当客户端第二次输入信息并回车时,控制台并没有跳转,和服务器端就不能通话了,下面是运行的结果:
客户端(我):
zoula
服务器:haoa
客户端(我):
quna
hh
kjkj
下面是我的代码:
服务器端的代码:
package com.my;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args) throws Exception{
ServerSocket server = null;
Socket client = null;
BufferedReader read = null;
PrintStream out = null;
BufferedReader serverInput = null;
server = new ServerSocket(5555);
boolean f = true;
while(f)
{
System.out.println("服务器端正在运行,等待客户端的连接。。。");
client = server.accept();
read = new BufferedReader(new InputStreamReader(client.getInputStream()));
serverInput = new BufferedReader(new InputStreamReader(System.in));
out = new PrintStream(client.getOutputStream());
boolean flag = true;
while(flag)
{
String str = read.readLine();
if(null == str || "".equals(str))
{
flag = false;
}else if("bye".equals(str))
{
flag = false;
}else
{
System.out.println("客户端:" + str);
boolean inflag = true;
while(inflag)
{
System.out.println("服务器(我):");
String inputStr = serverInput.readLine();
if(inputStr == null || "".equals(inputStr))
{
System.out.println("请输入正确的信息。。。");
inflag = false;
}else
{
// System.out.println("服务器(我):" + inputStr);
out.println(inputStr);
}
}
}
}
out.close();
client.close();
}
server.close();
}
}
客户端的代码:
package com.my;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class MyClient {
public static void main(String[] args) throws Exception {
Socket client = null;
client = new Socket("localhost",5555);
BufferedReader buf = null;
PrintStream out = null;
BufferedReader input = null;
input = new BufferedReader(new InputStreamReader(System.in));
out = new PrintStream(client.getOutputStream());
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
boolean flag = true;
while(flag)
{
System.out.println("客户端(我):");
String str = input.readLine();
if(str == null || "".equals(str))
{
flag = false;
}else
{
out.println(str);
String serverStr = buf.readLine();
System.out.println("服务器:"+serverStr);
}
}
buf.close();
client.close();
}
}
------解决方案--------------------
整体逻辑没有问题,就一个地方粗心造成的。
Java code
if(inputStr == null || "".equals(inputStr))
{
System.out.println("请输入正确的信息。。。");
inflag = false;
}else
{
// System.out.println("服务器(我):" + inputStr);
out.println(inputStr);
}