cyq11111111
cyq11111111
2016-07-09 07:08

socket连接,关于String index out of range:-1?求大神帮忙!

为什么客户端一发消息,服务器端就出现String index out of range:-1?
服务器程序:
import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;
public class teste implements Runnable

{

public String latitude,longitude;
public int i=0;
public void run()

{

try
{

//创建ServerSocket

ServerSocket serverSocket = new ServerSocket(8080);

while (true)

{

//接受客户端请求

Socket client = serverSocket.accept();

System.out.println("accept");

try
{

//接收客户端消息

BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

String str = in.readLine();

System.out.println(" "+str);
in.close();

            }  
            catch (Exception e)  
            {  
                System.out.println(e.getMessage());  
                e.printStackTrace();  
            }  
            finally 
            {  
                //关闭 
                socket.close();
                serverSocket.close();
                client.close();
            }
        } 
    }  
    catch (Exception e)  
    {  
        System.out.println(e.getMessage());  
    }  
}
//main函数,开启服务器  
public static void main(String[] args)  
{  
    Thread desktopServerThread = new Thread(new teste());  
    desktopServerThread.start();  
}  

}
客户端程序:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketClient {
public static void main(String[] args) {
try {
Socket socket =new Socket("192.168.1.238",8080);
socket.setSoTimeout(60000);

        PrintWriter printWriter =new PrintWriter(socket.getOutputStream(),true);
        BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(socket.getInputStream()));

        String result ="";
        while(result.indexOf("bye") == -1){
            BufferedReader sysBuff =new BufferedReader(new InputStreamReader(System.in));
            printWriter.println(sysBuff.readLine());
            printWriter.flush();

            result = bufferedReader.readLine();
            System.out.println("Server say : " + result);
        }

        printWriter.close();
        bufferedReader.close();
        socket.close();
    }catch (Exception e) {
        System.out.println("Exception:" + e);
    }
}

}

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答