1. 编程原理
1.1服务器端
(1) 创建ServerSocket对象,绑定监听端口;
(2) 通过accept()方法监听客户端请求;
(3) 连接建立后,通过输入流读取客户端发送的请求信息;
(4) 通过输出流向客户端发送相应信息;
(5) 关闭响应资源。
1.2 客户端
(1) 创建Socket对象,指明需要连接的服务器地址和端口;
(2) 连接建立后,通过输出流向服务器端发送请求信息;
(3) 通过输入流获取服务器端返回的响应信息;
(4) 关闭响应资源。
2. 编程实现
2.1 服务器端
<code>
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TestSocketServer {
public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
try{
ServerSocket ss = new ServerSocket(5888);//创建ServerSocket对象,绑定监听端口
Socket socket = ss.accept();//接受来自客户端的请求
in = socket.getInputStream();//得到来自客户端写入的数据
out = socket.getOutputStream();//服务器端输出流对象
DataOutputStream dos = new DataOutputStream(out);
DataInputStream dis = new DataInputStream(in);
String s =null;//定义从客户端读出的字符串
//如果读出的不为空的话。向客户端发出本机的ip地址和连接的端口号
if((s = dis.readUTF()) != null){
System.out.println(s);
System.out.println("from: " + socket.getInetAddress());
System.out.println("port: " + socket.getPort());
}
dos.writeUTF("hello success");//向客户端写入
dis.close();//关闭流对象
dos.close();
socket.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
</code>
2.2 客户端
<code>
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TestSocketClient {
public static void main(String[] args) {
InputStream is = null;
OutputStream os = null;
try{
Socket socket = new Socket("localhost", 5888);//创建Socket对象,指明需要连接的服务器的地址和端口号
is = socket.getInputStream();
os = socket.getOutputStream();
DataInputStream dis = new DataInputStream(is);
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("hello");//连接建立后,通过输出流向服务器端发送请求信息
String s = null;
if((s = dis.readUTF()) != null){
System.out.println(s);//通过输入流获取服务器响应的信息
}
dos.close();
dis.close();
socket.close();
} catch (UnknownHostException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
</code>