图片来自网络
【服务端】
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务端
public class MyServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
try {
//创建监听1515端口的ServerSocket对象
serverSocket = new ServerSocket(1515);
//堵塞等待客户端的请求,当收到请求就返回Socket对象
socket = serverSocket.accept();
//从Socket对象获取输入流和输出流
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
//通过输入流读取客户端发送的数据
byte[] bt = new byte[1024];
int len = in.read(bt);
String data = new String(bt, 0, len);
System.out.println(data);
//通过输出流向客户端返回数据
out.write("服务器已收到!!!".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
【客户端】
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
//客户端
public class MyClient {
public static void main(String[] args) {
Socket socket = null;
try {
//创建连接服务端的Socket对象
socket = new Socket("127.0.0.1", 1515);
//从Socket对象获取输入流和输出流
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
//通过输出流向服务端发送数据
out.write("来自客户端!!!".getBytes());
//通过输入流读取服务端返回的数据
byte[] bt = new byte[1024];
int len = in.read(bt);
String data = new String(bt, 0, len);
System.out.println(data);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}