网络编程.ServerSocket与Socket通信
0.服务端
public class NBServer {
public static void main(String[] args) {
doServer();
}
public static void doServer() {
ServerSocket server = null;
Socket socket = null;
InputStream is = null;
OutputStream os = null;
try {
server = new ServerSocket(6666);
while ((socket = server.accept()) != null) {
is = socket.getInputStream();
byte[] by = new byte[1024];
int len = 0;
while ((len = is.read(by)) != -1) {
System.out.println(new String(by, 0, len));
}
socket.shutdownInput();
os = socket.getOutputStream();
os.write("ok ig nb".getBytes());
os.flush();
socket.shutdownOutput();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(os);
close(is, socket);
close(server);
}
}
public static void close(ServerSocket server) {
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void close(InputStream is, Socket socket) {
close(is);
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.客户端
public class NBClient {
public static void main(String[] args) {
doClient();
}
public static void doClient() {
InputStream is = null;
OutputStream os = null;
Socket socket = null;
try {
socket = new Socket("localhost", 6666);
os = socket.getOutputStream();
os.write("out stream".getBytes());
os.flush();
socket.shutdownOutput();
is = socket.getInputStream();
byte[] by = new byte[1024];
int len = 0;
while((len = is.read(by)) != -1) {
System.out.println(new String(by, 0, len));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
NBServer.close(is, os, socket);
}
}
}