先启动服务器端程序,再启动客户端程序。先由客户端发送一行字符串过去,服务器收到后再返回一个字符串,现在一运行程序就卡死了,求解? 服务器端代码如下:

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();
 }
}

1个回答

server:

import java.io.*; 
import java.net.*; 

public class MyServer { 
public static void main(String[] args) throws IOException{ 
ServerSocket server=new ServerSocket(5678); 
Socket client=server.accept(); 
BufferedReader in=
new BufferedReader(new InputStreamReader(client.getInputStream())); 
PrintWriter out=new PrintWriter(client.getOutputStream()); 
while(true){ 
String str=in.readLine(); 
System.out.println(str); 
out.println("has receive...."); 
out.flush(); 
if(str.equals("end")) 
break; 
} 
client.close(); 
} 
} 

client:

import java.net.*; 
import java.io.*; 

public class Client{ 
static Socket server; 

public static void main(String[] args)throws Exception{ 
server=new Socket(InetAddress.getLocalHost(),5678); 
BufferedReader in=
new BufferedReader(new InputStreamReader(server.getInputStream())); 
PrintWriter out=new PrintWriter(server.getOutputStream()); 
BufferedReader wt=new BufferedReader(new InputStreamReader(System.in)); 

while(true){ 
String str=wt.readLine(); 
out.println(str); 
out.flush(); 
if(str.equals("end")){ 
break; 
} 
System.out.println(in.readLine()); 
} 
server.close(); 
} 
}