引言:作为ctrl cv工程师,实现用socket通信连续收发信息这个功能,却还是废了一些功夫,特此记录。
本文将分为三部分示例,示例将会层层推进。第一部分展示如何实现socket客户端向服务端发消息;第二部分展示如何实现socket服务端向客户端发送消息;第三部分展示如何实现socket客户端和服务端相互发消息。
客户端向服务端发消息
我们将实现通过socket客户端向服务端发消息,服务端接收消息并展示
- 编写服务端(
SocketServer.java
)代码
import java.io.DataInputStream;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
public class SocketServer {
public static void main(String[] args) throws IOException {
int port = 1573;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("ServerSocket创建成功,地址为 " + getLocalIP() + ":" + port);
System.out.println("等待接收客户端消息...");
Socket socket = serverSocket.accept();
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
String read = dataInputStream.readUTF();
System.out.println("收到来自客服端的消息:" + read);
}
/**
* 获取本机IP
* @return 本机IP,获取失败则返回 "0.0.0.0"
* @throws SocketException
*/
public static String getLocalIP() throws SocketException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while(networkInterfaces.hasMoreElements()) {
NetworkInterface next = networkInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = next.getInetAddresses();
while(inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
return "0.0.0.0";
}
}
- 编写客户端(
SocketClient.java
)代码
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class SocketClient {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入ip");
String ip = scanner.next();
System.out.println("请输入端口");
int port = scanner.nextInt();
String url = ip + ":" + port;
System.out.println("我们即将连接 →\n " + url);
Socket socket = new Socket(ip, port);
System.out.println("socket连接成功,请输入要发送的内容:");
String sendToServer = scanner.next();
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(sendToServer);
dataOutputStream.flush();
System.out.println("发送成功");
dataOutputStream.close();
}
}
- 编译并运行服务端代码
javac -Dfile.encoding=UTF-8 SocketServer.java
java SocketServer
- 编译并运行客户端代码
javac -Dfile.encoding=UTF-8 SocketClient.java
java SocketClient
客户端和服务端运行后如下图
客户端和服务端运行后我们在客户端输入ip和端口(ip和端口和服务端对应),以连接服务端
客户端连接上服务端我们在客户端继续输入要发送的内容
客户端发送内容可以看到,服务端正常接收到客户端发送过来的消息
服务端向客户端发消息
我们将实现通过socket服务端向客户端发消息,客户端接收消息并展示
修改服务端(SocketServer.java
)代码
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
String sendBackToClient = "哈喽,我是服务端,要不起";
System.out.println("将要发送到客户端的内容:" + sendBackToClient);
dataOutputStream.write(sendBackToClient.getBytes());
dataOutputStream.flush();
代码对比如下:
修改服务端(`SocketServer.java`)代码修改客户端(SocketClient.java
)代码
System.out.println(" →→ 等待接收服务端发来的消息!");
int bufferSize = 16 * 1024;
byte[] buffer = new byte[bufferSize];
try {
int readCount = socket.getInputStream().read(buffer);
String read = new String(buffer, 0, readCount);
System.out.println(" →→ 收到来自服务端的消息:" + read);
} catch (IOException e) {
throw new RuntimeException(e);
}
代码对比如下:
修改客户端(`SocketClient.java`)代码运行结果如下:
服务端发送内容互发消息
有了前面的两个章节,实现服务器与客户端互发消息只是代码结构的问题
修改服务端(SocketServer.java
)代码
Scanner scanner = new Scanner(System.in);
int bufferSize = 16 * 1024;
byte[] buffer = new byte[bufferSize];
boolean runningFlag = true;
try {
while (runningFlag) {
int readCount = socket.getInputStream().read(buffer);
String read2 = new String(buffer, 0, readCount);
System.out.print("客户端出:" + read2 + ", 那我出:");
String will = scanner.next();
dataOutputStream.write(will.getBytes());
dataOutputStream.flush();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
代码对比如下:
修改服务端(`SocketServer.java`)代码修改客户端(SocketClient.java
)代码
boolean runningFlag = true;
try {
while (runningFlag) {
int readCount = socket.getInputStream().read(buffer);
String read = new String(buffer, 0, readCount);
System.out.print("服务器出:" + read + ", 那我出:");
String will = scanner.next();
dataOutputStream.write(will.getBytes());
dataOutputStream.flush();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
代码对比如下:
修改客户端(`SocketClient.java`)代码运行结果如下:
互发内容以上,仅供参考,收工!
网友评论