javasocket编程
时间: 2023-09-04 15:15:41 浏览: 162
java socket编程
Java Socket编程是利用Java语言提供的Socket类和ServerSocket类,实现TCP/IP协议的网络编程。它可以实现客户端和服务器之间的双向通信。
下面是一个简单的Java Socket编程示例:
1. 服务器端代码
```java
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8888); //创建服务器Socket,绑定端口号为8888
System.out.println("服务器已启动,等待客户端连接...");
Socket socket = server.accept(); //等待客户端连接,程序阻塞在此处
System.out.println("客户端已连接:" + socket.getRemoteSocketAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //获取输入流
PrintWriter out = new PrintWriter(socket.getOutputStream()); //获取输出流
String msg;
while ((msg = in.readLine()) != null) { //循环读取客户端发来的消息
System.out.println("客户端发来消息:" + msg);
out.println("服务端已收到消息:" + msg); //将收到的消息回传给客户端
out.flush(); //刷新输出流
}
in.close(); //关闭输入流
out.close(); //关闭输出流
socket.close(); //关闭Socket连接
server.close(); //关闭ServerSocket
}
}
```
2. 客户端代码
```java
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888); //创建客户端Socket,连接到本机的8888端口
System.out.println("连接成功:" + socket.getLocalSocketAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //获取输入流
PrintWriter out = new PrintWriter(socket.getOutputStream()); //获取输出流
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //获取控制台输入流
String msg;
while ((msg = reader.readLine()) != null) { //循环读取控制台输入的消息
out.println(msg); //将消息发送给服务器
out.flush(); //刷新输出流
System.out.println("发送消息:" + msg);
System.out.println("服务器回复:" + in.readLine()); //读取服务器回传的消息
}
in.close(); //关闭输入流
out.close(); //关闭输出流
socket.close(); //关闭Socket连接
}
}
```
上面的代码演示了一个简单的客户端和服务器之间的通信,客户端向服务器发送消息,服务器收到消息后将消息回传给客户端。你可以根据实际需求,对这段代码进行修改和扩展。
阅读全文