分布式通信-tcp/ip 单播

时间:2021-09-25 01:06:02

服务端

public class SingleBroadCastSocketServer {

    public static void main(String[] args) {
ServerSocket serverSocket = null; try {
serverSocket = new ServerSocket(8888); //启动一个服务
while (true) {
final Socket socket = serverSocket.accept(); //监听客户端接入
System.out.println("start while");
new Thread(new Runnable() {
public void run() {
System.out.println("start thread");
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream())); while (true){
System.out.println("read data start");
String clientData = bufferedReader.readLine();
if(clientData ==null){
System.out.println("read data is null");
break;
} System.out.println("服务端接收到的数据:"+clientData); printWriter.println("data from server");
printWriter.flush();
}
} catch (IOException e) {
e.printStackTrace();
} }
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} } }

客户端

/**
* 单播-客戶端
*/
public class SingleBroadCastSocketClient { public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));//读取服务端数据
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true); //往服务器写数据
System.out.println("client set data"); //printWriter.write("data from client");
//write()方法,本身不会写入换行符,如果用write()写入了信息,在另一端如果用readLine()方法。由于读不到换行符,意味中读不到结束标记,然后由于IO流是阻塞式的,所以程序就是一直卡在那里不动了。原因即为缺少回车标识。如果在写入的时候加上“\r\n”,就可以解决这个问题了。而println()就自动加上了换行符了。 printWriter.println("data from client");
while (true){
System.out.println("client rec data");
String serverData = reader.readLine();
System.out.println("client rec data start");
if(serverData==null){
break;
}
System.out.println("客户端收到数据:"+serverData);
}
printWriter.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
} }
}