一、服务端流程
- 建立一个服务器Socket 指定端口并开始监听
serverSocket=new ServerSocket(8800);
- 使用 accept()方法,等待客户端触发通信
socket = serverSocket.accept();
- 打开输入流
is = socket.getInputStream();
- 获取客户端的信息,从输入流中读取信息
br = new BufferedReader(new InputStreamReader(is));
package com.xx.test_a;
/**
* 服务端
*/
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
ServerSocket serverSocket =null;
Socket socket =null;
InputStream is = null;
OutputStream os = null;
BufferedReader br =null;
try {
serverSocket=new ServerSocket(8800);
socket = serverSocket.accept();
is = socket.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
String info = null;
while((info=br.readLine())!=null){
System.out.println("这里是服务端!\n接收到的信息为:"+info);
}
os = socket.getOutputStream();
os.write("我是服务端,收到!".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br!=null){
br.close();
}
if (is!=null){
is.close();
}
if (socket!=null){
socket.close();
}
if (serverSocket!=null){
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
二、客户端流程
- 建立客户端的Socket连接,指定服务器的位置和端口
socket = new Socket("localhost",8800);
- 打开输出流
os = socket.getOutputStream();
package com.xx.test_a;
import java.io.*;
import java.net.Socket;
/**
* 客户端
*/
public class Client {
public static void main(String[] args) {
Socket socket =null;
OutputStream os = null;
InputStream is = null;
BufferedReader br = null;
try {
socket = new Socket("localhost",8800);
os = socket.getOutputStream();
String info = "我是客户端,测试!";
os.write(info.getBytes());
socket.shutdownOutput();
is = socket.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
String str ="";
while ((str = br.readLine())!=null){
System.out.println("这里是客户端!\n接收到的信息为:"+str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
三、运行结果
服务端:
客户端: