先启动服务器端程序,再启动客户端程序。先由客户端发送一行字符串过去,服务器收到后再返回一个字符串,现在一运行程序就卡死了,求解?
服务器端代码如下:
public class ServerTest
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(4000);
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
String str = "";
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer, 0, buffer.length)) != -1)
{
str += new String(buffer, 0, len);
}
System.out.println("客户端发送数据为:" + str);
OutputStream os = socket.getOutputStream();
os.write("hello".getBytes());
socket.close();
}
}
客户端代码为:
public class ClientTest
{
public static void main(String[] args) throws Exception
{
Socket socket = new Socket("127.0.0.1", 4000);
OutputStream os = socket.getOutputStream();
os.write("你好,服务器!".getBytes());
os.flush();
InputStream is = socket.getInputStream();
int len = 0;
byte[] buffer = new byte[1024];
String str = "";
while ((len = is.read(buffer, 0, buffer.length)) != -1)
{
str += new String(buffer, 0, len);
}
System.out.println("服务器发送数据为:" + str);
socket.close();
}
}
这个当然卡死啦,服务端一启动就close了,然后客户端去连服务端,没有服务响应,就会卡一会的,看看http://hi.baidu.com/lazycat0762/blog/item/22a0afb04fc917abd8335a8a.html这个
服务器不会一启动就close掉啊。服务器启动后会停在 Socket socket = ss.accept();这里,等待客户端的连接。如果把客户端接收服务器端的代码注释掉,服务器端就可以收到客户端的数据了。
@doctoryang: 不好意思我看成是C#的了,你再仔细看看这篇文章http://daoyongyu.iteye.com/blog/265677
int len = 0;这里定义有点问题。
如果len初始化为0,下面的while loop的条件应该是while ((len = is.read(buffer, 0, buffer.length)) > 0).
如果len初始化为-1,下面的while loop的条件可以是while ((len = is.read(buffer, 0, buffer.length)) != -1)