package netty;
//1.服务端
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
package netty;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
DataInputStream dataInputStream=null;
DataOutputStream dataOutputStream=null;
Socket socket=null;
try {
ServerSocket serverSocket=new ServerSocket(12345);
System.out.println("查询天气服务");
socket=serverSocket.accept();
dataInputStream=new DataInputStream(socket.getInputStream());
dataOutputStream=new DataOutputStream(socket.getOutputStream());
String readUTF = dataInputStream.readUTF();
System.out.println("服务器端接收到信息"+readUTF);
String result="晴天";
dataOutputStream.writeUTF(result);
System.out.println("发送给客户端");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
dataInputStream.close();
dataOutputStream.close();
socket.close();
}
}
}
服务端用socket=serverSocket.accept();进入等待状态,等待客户端发出请求。接收到请求后,返回请求结果
//2.客户端
public class Client {
public static void main(String[] args) throws IOException {
Socket socket=new Socket("127.0.0.1", 12345);
DataInputStream dataInputStream=null;
DataOutputStream dataOutputStream=null;
try {
dataOutputStream=new DataOutputStream(socket.getOutputStream());
String request="今天天气如何";
dataOutputStream.writeUTF(request);
System.out.println("客户端发出请求"+request);
dataInputStream=new DataInputStream(socket.getInputStream());
String readUTF = dataInputStream.readUTF();
System.out.println("客户端收到信息:"+readUTF);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
socket.close();
dataInputStream.close();
dataOutputStream.close();
}
}
}
客户端用Socket连接到服务器,给服务器发送信息,并收到服务端的响应信息。
基本的Socket通信
最新推荐文章于 2024-04-10 16:53:26 发布