java的socket编程的代码
时间: 2023-11-30 10:01:47 浏览: 55
你可以参考以下Java Socket编程的基本代码框架:
客户端代码:
```
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
// 与服务器建立连接
Socket socket = new Socket("localhost", 8888);
// 发送信息
OutputStream outputStream = socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write("客户端发送消息");
bufferedWriter.flush();
// 接收信息
InputStream inputStream = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String response = bufferedReader.readLine();
System.out.println("接收消息:" + response);
// 关闭流和socket
bufferedReader.close();
bufferedWriter.close();
socket.close();
}
}
```
服务器端代码:
```
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端连接成功!");
// 接收信息
InputStream inputStream = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String message = bufferedReader.readLine();
System.out.println("接收到客户端的消息:" + message);
// 发送信息
OutputStream outputStream = socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write("服务器返回消息");
bufferedWriter.flush();
// 关闭流和socket
bufferedReader.close();
bufferedWriter.close();
socket.close();
}
}
```
以上是Java Socket基本编程框架,可以根据自己的需求进行修改和优化。
阅读全文