客户端:
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.util.Scanner;
public class sockclient {
public static void main(String[] args) {
try {
String host = "127.0.0.1";
int port = 8888;
Socket socket = new Socket(host,port);
OutputStream outputstream = socket.getOutputStream();
System.out.println("(Enter your Message): ");
String m = null;
String t;
Scanner s = new Scanner(System.in);
if(s.hasNext()) {
m = s.nextLine();
}
s.close();
t = "(Send)" + m;
System.out.println(t);
byte[] SendByte = m.getBytes("GBK");
OutputStream output = socket.getOutputStream();
output.write(SendByte);
byte[] GetByte = new byte[2048];
InputStream input = socket.getInputStream();
int read = input.read(GetByte);
System.out.println("(Server) " + new String(GetByte,0,read,Charset.defaultCharset()));
output.close();
socket.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
服务端:
import java.io.InputStream;
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
import java.util.*;
public class sockserver {
public static void main(String args[]) throws Exception {
int port = 8888;
ServerSocket server = new ServerSocket(port);
System.out.println("(Listening)Port " + port);
ExecutorService TPool = Executors.newFixedThreadPool(100);
while(true) {
Socket s = server.accept();
Runnable runnable=()-> {
try {
byte[] Bytes = new byte[2048];
InputStream input = s.getInputStream();
int Length;
StringBuilder sb = new StringBuilder();
while((Length = input.read(Bytes)) != -1) {
sb.append(new String(Bytes,0,Length,"GBK"));
}
System.out.println("(Recv) " + sb);
OutputStream out = s.getOutputStream();
String n = "Receive your Message";
byte[] Send = n.getBytes();
out.write(Send);
input.close();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
};
TPool.submit(runnable);
}
}
}
请问各位博主,以上代码存在哪些问题导致只有客户端退出,服务的才会收到消息