标签:
服务端编写步骤:
利用ServerSocket建立对服务端某个端口的监听;
利用accept方法穿件服务端Socket
利用已建立的socket创建输入输出流
关闭输入输出流 关闭socket 关闭Server
public class Server {
public Server() {
try {
ServerSocket server = new ServerSocket(8090);
System.out.println("服务器启动,等待客户端请求...");
// while (true) {
Socket socket = server.accept();// 监听客户端的请求
// 服务器接收客户端的请求
InputStream in = socket.getInputStream();
byte[] by = new byte[1024];
in.read(by);
System.out.println("服务器端接收到了客户端的请求信息:" + new String(by).trim());
// 服务器响应信息返回给客户端
OutputStream out = socket.getOutputStream();
out.write("Hello".getBytes());
in.close();
out.close();
socket.close();
server.close();
// }
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Server();
}
}
客户端编写步骤
创建客户端Socket向服务器发起连接请求
利用已建立的Socket创建输入输出流
关闭输入输出流,关闭socket 关闭server
public class Client {
public Client(){
try {
String input_info = JOptionPane.showInputDialog(null,"请输入请求信息");
Socket socket = new Socket("127.0.0.1", 8090);
//客户端向服务器发送请求
OutputStream out = socket.getOutputStream();
out.write(input_info.getBytes());
//客户端接收服务器的响应
InputStream in = socket.getInputStream();
byte [] b = new byte[1024];
System.out.println(b.length);
in.read(b);
System.out.println("客户端接收到服务器端的响应信息:" + new String(b).trim());
out.close();
in.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new Client();
}
}
标签:
原文地址:http://www.cnblogs.com/CMCM/p/5300178.html