Java Socket简单实现客户端与服务端通信
实现Socket通信的步骤
创建一个ServerSocket监听8888端口
等待请求
接收到请求之后使用socket进行通信,创建BufferedReader用于读取数据
创建PrintWriter,用于发送数据
关闭资源
服务端代码
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by RogerLaw on 2016/10/10.
*/
public class Server2 {
public static void main(String[] args) {
try {
//创建一个ServerSocket监听8888端口
ServerSocket serverSocket=new ServerSocket(8888);
//等待请求
Socket socket=serverSocket.accept();
//接收到请求之后使用socket进行通信,创建BufferedReader用于读取数据
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line=is.readLine();
System.out.println("received form client:"+line);
//创建PrintWriter,用于发送数据
PrintWriter printWriter=new PrintWriter(socket.getOutputStream());
printWriter.println("received data"+line);
printWriter.flush();
//关闭资源
printWriter.close();
is.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端代码
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* Created by RogerLaw on 2016/10/10.
*/
public class Client2 {
public static void main(String[] args) {
String msg="Client Data";
try {
//创建一个Socket和本地的8888端口连接
Socket socket=new Socket("127.0.0.1",8888);
//使用Socket创建PrintWriter和PrintBufferedReader进行读写数据
PrintWriter printWriter=new PrintWriter(socket.getOutputStream());
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//发送数据
printWriter.println(msg);
printWriter.flush();
//接收数据
String line=is.readLine();
System.out.println("received from server:"+line);
//关闭资源
printWriter.close();
is.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}