当前位置: 技术问答>java相关
不能用Socket或是ServerSocket读取数据
来源: 互联网 发布时间:2015-07-01
本文导语: 我参考Thinking Java 及其他人的例子写了一对简单的测试程序如下,现在的问题是不管哪一方都读不了数据,走到读数据的地方就吊死了,我如果加了setSoTimeout就永远超时,反正是什么都得不到。但如果我的客户端程...
我参考Thinking Java 及其他人的例子写了一对简单的测试程序如下,现在的问题是不管哪一方都读不了数据,走到读数据的地方就吊死了,我如果加了setSoTimeout就永远超时,反正是什么都得不到。但如果我的客户端程序往一个VB的测试程序发数据,VB就收得到,这个VB程序是我以前为VC写的测试模块,久经考验,肯定没问题。所以肯定是读数据的问题。
请各位高手帮忙看看,指点迷津。
客户端主程序:
try
{
s = new Socket("160.0.99.79",8090);//Socket客户端用它初始连接一次
s.setSoTimeout(500);
PrintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
s.getOutputStream())),true);
out.print("mytest.mytest");
out.flush();
BufferedReader in =
new BufferedReader(
new InputStreamReader(
s.getInputStream()));
String str = in.readLine();
System.out.println(str);
}
catch( SocketException Se )
{
... ...
}
catch( IOException IOe )
{
... ...
}
SERVER端主程序:
ServerSocket s = new ServerSocket(8090);
System.out.println("Started: " + s);
// Blocks until a connection occurs:
Socket socket = s.accept();
try
{
System.out.println(
"Connection accepted: "+ socket);
BufferedReader in =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
// Output is automatically flushed
// by PrintWriter:
PrintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())),true);
while (true)
{
String str = in.readLine();
if (str.equals("END")) break;
System.out.println("Echoing: " + str);
out.println(str);
}
// Always close the two sockets...
}
请各位高手帮忙看看,指点迷津。
客户端主程序:
try
{
s = new Socket("160.0.99.79",8090);//Socket客户端用它初始连接一次
s.setSoTimeout(500);
PrintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
s.getOutputStream())),true);
out.print("mytest.mytest");
out.flush();
BufferedReader in =
new BufferedReader(
new InputStreamReader(
s.getInputStream()));
String str = in.readLine();
System.out.println(str);
}
catch( SocketException Se )
{
... ...
}
catch( IOException IOe )
{
... ...
}
SERVER端主程序:
ServerSocket s = new ServerSocket(8090);
System.out.println("Started: " + s);
// Blocks until a connection occurs:
Socket socket = s.accept();
try
{
System.out.println(
"Connection accepted: "+ socket);
BufferedReader in =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
// Output is automatically flushed
// by PrintWriter:
PrintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())),true);
while (true)
{
String str = in.readLine();
if (str.equals("END")) break;
System.out.println("Echoing: " + str);
out.println(str);
}
// Always close the two sockets...
}
|
vb 送的字串后加一个vbCrLf 试试
|
我试了一下你的程序,是没问题的.
你的问题在于SERVER端接收是
String str = in.readLine();
而客户端发送out.print("mytest.mytest");没有加"n",
服务器自然没有反应.
你的问题在于SERVER端接收是
String str = in.readLine();
而客户端发送out.print("mytest.mytest");没有加"n",
服务器自然没有反应.