62,614
社区成员
发帖
与我相关
我的任务
分享
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(9052);
System.out.println("开始等待某个连接");
do{
Socket s = ss.accept();
System.out.println("获取到一个连接");
DataInputStream in = new DataInputStream(s.getInputStream());
byte[] result =new byte[100000];
int thislength = 0;
int totallength= 0;
do {
thislength = in.read(result, totallength, 2000);
if(thislength>0)
{
totallength +=thislength;
}
} while (thislength>0);
byte[] response = new byte[totallength];
System.arraycopy(result, 0, response, 0, totallength);
String responseStr = new String(response);
System.out.println("服务端接收:" + responseStr);
String str="服务端发送"+responseStr;
DataOutputStream out = new DataOutputStream(s.getOutputStream());
out.write(str.getBytes());
System.out.println(str);
out.flush();
}while(true);
// ss.close();
}
thislength = in.read(result, totallength, 2000);
你调试下,应该阻塞在这,这种交互你需要一个简单的协议,另外data装饰类没太大意义
System.out.println("服务端接收:" + responseStr);
服务端能执行到这句么,感觉很悬呢public static void main(String[] args) throws Exception {
int i=0;
while(i<10){
Socket s = new Socket("127.0.0.1",9052);
String str="客户端发送"+i;
DataOutputStream out = new DataOutputStream(s.getOutputStream());
out.write(str.getBytes());
System.out.println(str);
out.flush();
//到这里就执行不下去了
DataInputStream in = new DataInputStream(s.getInputStream());
byte[] result =new byte[100000];
int len;
int thislength = 0;
int totallength= 0;
do {
thislength = in.read(result, totallength, 2000);
if(thislength>0)
{
totallength +=thislength;
}
} while (in.available()>0);
byte[] response = new byte[totallength];
System.arraycopy(result, 0, response, 0, totallength);
String responseStr = new String(response);
System.out.println("服务端接收:" + responseStr);
out.close();
in.close();
i++;
}}
如果把
DataInputStream in = new DataInputStream(s.getInputStream());
byte[] result =new byte[100000];
int len;
int thislength = 0;
int totallength= 0;
do {
thislength = in.read(result, totallength, 2000);
if(thislength>0)
{
totallength +=thislength;
}
} while (in.available()>0);
byte[] response = new byte[totallength];
System.arraycopy(result, 0, response, 0, totallength);
String responseStr = new String(response);
System.out.println("服务端接收:" + responseStr);
out.close();
in.close();
这一段注释掉就能执行了 但是不能接收啊
求大家帮忙解决……