1、服务端代码:
public class server {
public static void main(String[] args) {
int port = 9090;// 端口
try {
// 1、监听端口
ServerSocket serverSocket = new ServerSocket(port);
// 2、等待读取数据
Socket socket = serverSocket.accept();
// 3、读取数据准备
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
// 4、读取数据
String str = br.readLine();
// 5、按照通讯的协议对数据进行解读
System.out.println(socket.getRemoteSocketAddress() + "说:" + str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
2、客户端:
public class client {
public static void main(String[] args) {
String ipAddress = "192.168.0.10";
int port = 9090;
try {
Socket socket = new Socket(ipAddress, port);
PrintWriter pw = new PrintWriter(socket.getOutputStream());
Scanner scan = new Scanner(System.in);
String str = "";
while (scan.hasNext()) {
str = scan.nextLine();
pw.println(str);
pw.flush();
System.out.println("客户端发送了:" + str);
}
scan.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
简单的Socket编程Java实现就完成了。。。