int count = is.read(buffer); String str = new String(buffer,0,count); System.out.println("收到了服务器的返回数据:" + str); 这段其中IS 直接用InputStream is = socket.getInputStream() 不用DataInputSream撒
用 while (flag) { int i = dis.read(b); temp = new String(b, 0, i); if (temp.endsWith("0D")) flag = false; System.out.println(temp); } 读取数据时,经常报java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.checkBounds(Unknown Source) at java.lang.String.<init>(Unknown Source) at com.love999.testserver.rece.ReceThread.run(ReceThread.java:28) at java.lang.Thread.run(Unknown Source) 请问这是什么原因造成的?谢谢!
难道你们通过socket通讯,都不制定传输协议,不打招呼的?各做各的?
用的是TCP协议啊,先建立连接,然后他给我回应,我在发送用户名和密码登陆,给我回应登陆信息,然后我在传数据给他,问题时他能收到我的数据,我收不到他的回应信息。。
我这里说的协议,不是指底层的TCP,是说的消息格式。也就是你这里说的用户名,密码,回应信息的格式比如,这个用户名和密码是怎么发过去的?
writeUTF(用户名);writeUTF(密码);?那回应信息呢?是一个byte?还是一个字符串?字符串的话是按什么格式呢?
byte[] b = new byte[512];
String temp = "";
try {
dis = new DataInputStream(socket.getInputStream());
osw = new OutputStreamWriter(socket.getOutputStream());
osw.write(userInfor);
osw.flush();
System.out.println("发送C1(用户登录)数据包:" + userInfor +" 发送C1(用户登录)数据包:" + userInfor.length());
while(true){
int i = dis.read(b);//这个地方报错
temp = new String(b,0,i);
if(temp.endsWith("0D"))
break;
}
System.out.println("服务器回应:"+temp);
没找到呀!最好将路径设成全局变量,这样写和读的路径一样,应该不会出问题!
dis是DataInputStream的实例,你从哪的API看到Socket有read方法?
public SocketClient()
{
try {
sc = new Socket("localhost",1234);
//服务器的IP和端口
is = sc.getInputStream();
os = sc.getOutputStream();
} catch (UnknownHostException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} }
public void sendToServer(String str)
{
try {
System.out.println("请数据你要发送到服务器的数据:");
os.write(str .getBytes());
System.out.println("向服务器发送了数据:" + str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String receive()
{
try {
int count = is.read(buffer);
String str = new String(buffer,0,count);
System.out.println("收到了服务器的返回数据:" + str);
return str;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public void closeconnection()
{
try {
is.close();
os.close();
sc.close();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
String str = new String(buffer,0,count);
System.out.println("收到了服务器的返回数据:" + str); 这段其中IS 直接用InputStream is = socket.getInputStream()
不用DataInputSream撒
while (flag) {
int i = dis.read(b);
temp = new String(b, 0, i);
if (temp.endsWith("0D"))
flag = false;
System.out.println(temp);
}
读取数据时,经常报java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.checkBounds(Unknown Source)
at java.lang.String.<init>(Unknown Source)
at com.love999.testserver.rece.ReceThread.run(ReceThread.java:28)
at java.lang.Thread.run(Unknown Source)
请问这是什么原因造成的?谢谢!