java socket卡死的问题?
rzty1 2012-08-04 10:09:16 先启动服务器端程序,再启动客户端程序。先由客户端发送一行字符串过去,服务器收到后再返回一个字符串,现在一运行程序就卡死了,求解?
服务器端代码如下:
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();
}
}