访问端:
public static void main(String[] args) {
// initSocket();
testSocket();
}
public static void testSocket() {
try {
String host = "192.168.3.238";
int port = 8801;
if (!connectSocket(host, port)) {
System.out.println("connect fail");
return;
}
if (!sendData("test data".getBytes(StandardCharsets.UTF_8))) {
return;
}
if (!readData()) {
return;
}
System.out.println("return---" + returnData);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static boolean connectSocket(String host, int port) {
try {
socket = new Socket();
SocketAddress address = new InetSocketAddress(host, port);
socket.connect(address);
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
private static boolean closeSocket() {
if (!socket.isClosed()) {
try {
socket.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
return true;
}
public static boolean sendData(byte[] data) {
try {
OutputStream out = socket.getOutputStream();
out.write(("send data").getBytes(StandardCharsets.UTF_8));
out.flush();
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public static boolean readData() {
try {
int len = 0;
byte[] data = new byte[128];
InputStream in = socket.getInputStream();
len = in.read(data);
String instr = new String(data, 0, len);
// System.out.println("return message" + instr);
returnData = instr;
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
服务端main:
public static void main(String[] args) {
byte[] data = new byte[128];
int len = 0;
ServerSocket socket = null;
try {
socket = new ServerSocket(8801);
System.out.println("socket 套接字创建成功,等待连接...");
while (true) {
Socket con = socket.accept();
SocketListenThread s_thread = new SocketListenThread(con);
s_thread.setSocket(con);
s_thread.start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket.isClosed()) {
System.out.println("socket已经关闭");
}
}
服务端线程:
public class SocketListenThread extends Thread {
/**
* socket
*/
private Socket socket;
@Override
public void run() {
try {
sleep(3000);
int len = 0;
s_in = socket.getInputStream();
len = s_in.read(data);
String in = new String(data, 0, len);
System.out.println("接收消息" + in);
if (socket.isClosed()) {
System.out.println("socket已经关闭1");
}
s_ou = socket.getOutputStream();
s_ou.write((in + "_a").getBytes(StandardCharsets.UTF_8));
s_ou.flush();
s_ou.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
说明:服务端会一直运行,等待接收访问,访问端每次访问都占用一个新的线程来处理当次访问
对于服务端和访问端,InputStream都为读数据内容,OutputSteam都为发送数据,在发送数据时,不要执行out.close();这样会将socket关闭。
每次读出的数据,都需要byte[]来接收,因为开始为128位,所有如果读的内容不足128,后面会出现乱码,需要截取对应的长度的数据,len = in.read(data);len即为数据真实长度,实际开发中可以自己指定长度。