服务端
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static final int PORT = 12345;
private static final String CHARSET_NAME = "UTF-8";
public static void main(String[] args) {
new Server().start();
}
private void start() {
try {
ServerSocket server = new ServerSocket(PORT);
System.out.println("服务端开启,等待客户端连接中...");
while (true) {
Socket socket = server.accept();
new TaskHandler (socket).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
class TaskHandler extends Thread {
private Socket socket;
private TaskHandler (Socket socket) {
this.socket = socket;
}
@Override
public void run() {
InputStream in = null;
OutputStream out = null;
try {
in = socket.getInputStream();
byte[] bytes = new byte[1024];
int len;
StringBuilder msg = new StringBuilder();
while ((len = in.read(bytes)) != -1) {
msg.append(new String(bytes, 0, len, CHARSET_NAME));
}
System.out.println("[客户端]:" + msg);
out = socket.getOutputStream();
out.write(("我已接收信息\"" + msg + "\"").getBytes(CHARSET_NAME));
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.getStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
客户端
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private static final String HOST = "127.0.0.1";
private static final int PORT = 12345;
private static final String CHARSET_NAME = "UTF-8";
public static void main(String args[]) {
new Client().start();
}
private void start() {
Socket socket = null;
InputStream in = null;
OutputStream out = null;
try {
socket = new Socket(HOST, PORT);
System.out.println("连接服务器成功");
out = socket.getOutputStream();
System.out.print("[客户端]:");
socket.getOutputStream().write(new Scanner(System.in).nextLine().getBytes(CHARSET_NAME));
socket.shutdownOutput();
in = socket.getInputStream();
byte[] bytes = new byte[1024];
int len;
StringBuilder msg = new StringBuilder();
while ((len = in.read(bytes)) != -1) {
msg.append(new String(bytes, 0, len, CHARSET_NAME));
}
System.out.println("[服务端]:" + msg);
in.close();
out.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}