socket服务端和客户端数据通信 数据交互
程序员文章站
2022-03-15 21:57:18
...
2014-03-10 11:30:28
服务器
package socket.example;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
/*
* 简单的socket服务端,实现和客户端的数据交换
*/
public class SocketServer {
public static final int PORT = 9999;//端口
public static void start() throws IOException {
// 建立服务监听
ServerSocket serverSocket = new ServerSocket(PORT);
Socket s = serverSocket.accept();
System.out.println("建立Socket链接!!!");
String serverMessage = "收到客户端呼叫!!!";
//服务端吧输入放到前面,输出放到后面
//接收客户端的信息
DataInputStream dis = new DataInputStream(new BufferedInputStream(s
.getInputStream()));
System.out.println("客户端呼叫显示===>>>>>>" + dis.readUTF());
//向客户端发送信息
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
ps.writeUTF(serverMessage);
ps.flush();//一定要写,负责客户端会进入等待状态
dis.close();
ps.close();
}
public static void main(String[] arge) throws UnknownHostException,
IOException {
SocketServer.start();
}
}
客户端
package socket.example;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
/*
* 简单的socket客户端,实现和服务端的数据交换
*/
public class SocketClient {
public static final String IP = "127.0.0.1";//服务端ip地址
public static final int PORT = 9999;//服务端监听端口
public static void start() throws UnknownHostException, IOException {
//创建socket链接
Socket s = new Socket(IP, PORT);
String clientMessage = "呼叫服务器端,请建立Socket链接";
System.out.println("Socket 客户端执行!!!!");
//向服务端发送消息
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
ps.writeUTF(clientMessage);
ps.flush();
//接收服务端的消息
DataInputStream dis = new DataInputStream(new BufferedInputStream(s
.getInputStream()));
System.out.println("服务器返回的信息====》》》》" + dis.readUTF());
dis.close();
ps.close();
}
public static void main(String[] arge) throws UnknownHostException,
IOException {
SocketClient.start();
}
}
转载自:http://blog.csdn.net/chinarenzhou/article/details/5750023