run()方法只是調用了一個函數﹐而沒有啟動線程﹐要啟動線程﹐不要用run(),而是要用start()方法
解决方案 »
- netbeans 6.8 uml
- 几道JAVA的基础题,请大家帮帮忙!谢谢!!救命题!!!
- 问一个很有意思又很难的java问题,如果能回答出来估计真的是高高手了!
- 数字签名问题,等待高手。。。。。。
- 关于java中使用jni实现ping功能的问题(linux系统)
- 请各位回答我几个分布式的问题!!!!!!!!!!!
- 请问如何把一个二维数组拷贝到另一个二维数组中??谢谢
- “汉字”中国古老的文化
- 请问java客户端报表打印提取数据时一定要用RMI吗?
- 求帮助一个双重for循环的算法,是在不知道怎么做
- 请问Java中的Socket和win中的socket以及VC中Socket有什么区别?
- 一个string类型的变量怎么变成int的,谢谢了
我的 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);