服务端:1.创建输入流和输出流 2.启动服务器端 3.创建监听客户端连接 4.读取客户端传递的信息 5.返回结果 6.关闭输出流和输入流
代码示例:
package com.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* socket编程,服务器端
* @author tingcai.liu
*
*/
public class SocketServer {
public static void main(String[] args) {
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
//启动socket服务端
try {
ServerSocket serverSocket = new ServerSocket(8888);
//加上while(true),让服务端一致保持运行,当有一个客户端连接成功以后,服务端就停止运行
while(true) {
//监听客户端连接,accept()方法是阻塞方法,如果没有客户端连接,其后的代码不会执行
Socket socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
//获得客户端传来的城市名称
String cityName = dataInputStream.readUTF();
System.out.println("from client..." + cityName);
//查询天气并返回结果
String result = "晴天";
dataOutputStream.writeUTF(result);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(dataOutputStream != null) {
dataOutputStream.close();
}
if(dataInputStream != null) {
dataInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客户端:1.创建输入流和输出流 2.创建socket连接 3.得到输出流 4.向服务器端发送数据 5.接收服务器端返回的数据 6.关闭socket连接,关闭输入流和输出流
代码示例:
package com.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Socket编程,客户端
* @author tingcai.liu
*
*/
public class SocketClient {
public static void main(String[] args) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
//创建Socket连接
socket = new Socket("127.0.01", 8888);
//得到输出流
dataOutputStream = new DataOutputStream(socket.getOutputStream());
//发送数据
dataOutputStream.writeUTF("西安");
//接收数据
dataInputStream = new DataInputStream(socket.getInputStream());
//得到输入流
String result = dataInputStream.readUTF();
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(socket != null) {
socket.close();
}
if(dataInputStream != null) {
dataInputStream.close();
}
if(dataOutputStream != null) {
dataOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}