【发布时间】:2015-07-09 16:04:43
【问题描述】:
我是网络编程的新手,以前从未使用 Java 进行网络编程。 我正在使用 Java 编写服务器,并且在处理来自客户端的消息时遇到了一些问题。我用过
DataInputStream inputFromClient = new DataInputStream( socket.getInputStream() );
while ( true ) {
// Receive radius from the client
byte[] r=new byte[256000];
inputFromClient.read(r);
String Ffss =new String(r);
System.out.println( "Received from client: " + Ffss );
System.out.print("Found Index :" );
System.out.println(Ffss.indexOf( '\a' ));
System.out.print("Found Index :" );
System.out.println(Ffss.indexOf( ' '));
String Str = new String("add 12341\n13243423");
String SubStr1 = new String("\n");
System.out.print("Found Index :" );
System.out.println( Str.indexOf( SubStr1 ));
}
如果我这样做,并且有一个示例输入 asg 23\aag,它将返回:
Found Index :-1
Found Index :3
Found Index :9
很明显,如果String对象是从头创建的,indexOf可以定位到“\”。 如果 String 是从处理 DataInputStream 中获得的,那么代码如何定位 \a 会有问题?
【问题讨论】:
-
不相关,但不要调用String的构造函数进行简单的字符串创建。例如更喜欢
String foo = "foo"而不是String foo = new String("foo") -
@TheLostMind 我没有从我的编辑器复制代码,这是一个错字
-
@SteveKuo 我打错字了,我在粘贴代码后做了一些改动。很抱歉造成混乱
标签: java network-programming substring indexof datainputstream