JAVA 网络编程基础步骤
*TCP编程服务器端步骤
1. 创建Socket,端口监听
ServerSocket serverSocket = new ServerSocket(4444);
2. 接受客户连接
Socket clientSocket = serverSocket.accept();
3. 创建读写对象
PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
4. 利用读写对象,与客户端通信
String inputLine, outputLine;
inputLine = in.readLine();
out.println(outputLine);
5. 关闭对象
out.close();
in.close();
clientSocket.close();
serverSocket.close();
*TCP编程客户端步骤
1. 创建Socket
Socket echoSocket = new Socket("Hostname", 7);
2. 创建读写对象
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
3. 利用读写对象,与服务器通信
String userString;
userString = in.readLine();
out.println(userString);
4. 关闭对象
out.close();
in.close();
echoSocket.close();
*UDP编程服务器端步骤
1. 创建socket
DatagramSocket socket = new DatagramSocket(4445);
2. 接受客户请求
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
3. 数据准备
String dString = new Date().toString();
buf = dString.getBytes();
4. 提取客户端信息
InetAddress address = packet.getAddress();
int port = packet.getPort();
5. 发送数据
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
6. 关闭对象
socket.close();
*UDP编程客户端步骤
1. 创建Socket
DatagramSocket socket = new DatagramSocket();
2. 准备服务器信息
byte[] buf = new byte[256];
InetAddress address = InetAddress.getByName("Hostname");
DatagramPacket packet = new DatagramPacket(buf,
buf.length, address, 4445);
3. 向服务器发送请求
socket.send(packet);
4. 从服务器读取信息
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
5. 关闭对象
socket.close();
凡是有该标志的文章,都是该blog博主Caoer(草儿)原创,凡是索引、收藏
、转载请注明来处和原文作者。非常感谢。