谢谢飞鱼指点!再一个进一步的问题 :D 搞定了结帖 我的 tServer.start() 调用的函数如下: void Listen(){ try{ s = new ServerSocket(3000, 20); while (true){ // Keeps fetching data sc = s.accept(); is = sc.getInputStream(); int length = is.available(); int totalLength = length; for (;length != 0; length -= 128){ // Keeps reading until the end; byte c[] = new byte[128]; try{ is.read(c, totalLength - length, 128); } catch (IOException ioex){ System.err.println("IO error occured while getting data from socket"); } finally{ str += new String(c); } } // Callback function here to return the string System.out.println("Got string: " + str); } } catch (IOException ioex){ System.err.println("Server Socket Creation Failed!"); } } 随后在另外一线程启动如下函数 try{ s = new java.net.Socket(this.remoteAddress, this.remotePort); OutputStream os = s.getOutputStream(); os.write(str.getBytes()); } catch (IOException ioex){ System.err.println("Failed to init socket to send data"); } 为什么最后打印出来只有 Got string: 后面空白?谢谢!
我有急事﹐馬上要走了﹐不過看了你的程序﹐有一個地方好像有問題 for (;length != 0; length -= 128){ // Keeps reading until the end; byte c[] = new byte[128]; c[]每次循環都重新創建﹐得到的值應不對﹐不過沒有仔細看﹐明天再給看一下﹐我走了
對不起﹐昨天太匆忙﹐看錯了。 有錯的地方應是 int length = is.available(); int totalLength = length;available()總是返回0﹐所以下面的循環總是沒有執行. 你可以這樣寫 Socket sc = s.accept(); InputStream is = sc.getInputStream(); byte[] buffer = new byte[1024]; int chars_read; String str = ""; while ((chars_read = is.read(buffer)) != -1 ) { str += new String(buffer,0,chars_read); } System.out.println("Got string: " + str);
我的 tServer.start() 调用的函数如下:
void Listen(){
try{
s = new ServerSocket(3000, 20);
while (true){ // Keeps fetching data
sc = s.accept();
is = sc.getInputStream();
int length = is.available();
int totalLength = length;
for (;length != 0; length -= 128){ // Keeps reading until the end;
byte c[] = new byte[128];
try{
is.read(c, totalLength - length, 128);
}
catch (IOException ioex){
System.err.println("IO error occured while getting data from socket");
}
finally{
str += new String(c);
}
}
// Callback function here to return the string
System.out.println("Got string: " + str);
}
}
catch (IOException ioex){
System.err.println("Server Socket Creation Failed!");
}
}
随后在另外一线程启动如下函数
try{
s = new java.net.Socket(this.remoteAddress, this.remotePort);
OutputStream os = s.getOutputStream();
os.write(str.getBytes());
}
catch (IOException ioex){
System.err.println("Failed to init socket to send data");
}
为什么最后打印出来只有 Got string: 后面空白?谢谢!
for (;length != 0; length -= 128){ // Keeps reading until the end;
byte c[] = new byte[128];
c[]每次循環都重新創建﹐得到的值應不對﹐不過沒有仔細看﹐明天再給看一下﹐我走了
有錯的地方應是
int length = is.available();
int totalLength = length;available()總是返回0﹐所以下面的循環總是沒有執行.
你可以這樣寫 Socket sc = s.accept();
InputStream is = sc.getInputStream();
byte[] buffer = new byte[1024];
int chars_read;
String str = "";
while ((chars_read = is.read(buffer)) != -1 ) {
str += new String(buffer,0,chars_read);
}
System.out.println("Got string: " + str);