下面贴代码,一个是server,一个是client
client:
package testClient;
import java.net.Socket;
import java.util.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
String str=null;
Socket client=new Socket("localhost",8819);
Scanner scan=new Scanner(client.getInputStream());
PrintWriter p=new PrintWriter(client.getOutputStream(),true);
Scanner scan2=new Scanner(new InputStreamReader(System.in));
scan2.useDelimiter("\n");
System.out.println("请输入要发送给服务端的字符串");
if(scan2.hasNext()) str=scan2.next().toString();
p.println(str);
client.shutdownOutput();
while(!scan.hasNext());
System.out.println(scan.next().toString());
}
}
下面是server:
package testServer;
import java.net.*;
import java.util.*;
import java.io.*;
public class server {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
String str=null;
ServerSocket s=new ServerSocket(8819);
System.out.println("已就绪,等待连接");
Scanner scan=new Scanner(new InputStreamReader(System.in));
Socket c=s.accept();
System.out.println("已连接上");
Scanner scan2=new Scanner(c.getInputStream());
scan2.useDelimiter("\n");
str=scan2.next();
if(str.equals(" hello world"))
{
PrintWriter w=new PrintWriter(c.getOutputStream());
w.println("已收到");
c.shutdownOutput();
}else
{
System.out.println("收到的字符串不正确");
System.out.println(str);
}
c.close();
}
}
请问是怎么回事?输出的字符串已说明接收到的str就是“hello world",但是str.equals("hello world")的结果却为false,请问这是怎么回事?
兄弟,你debug看一下就知道了,客户端用Scanner输入的字符串是带有换行符的,看下图,服务端截图
if(str.equals(" hello world"))多些了个空格吧
很可能是多了个空格的原因
是不是输入的时候打空格了,建议把hello word之间的空格去掉试一下。还有就是,建议equals语句的时候尽量把字符串放前面,变量放后面。因为str可能有null值得情况。
努力。。。。。。。。。
你没发现你的server类匹配语句有个空格吗?
if(str.equals(" hello world"))
把hello前面的空格去掉