网络基础

mch20093493 mch20093493 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
在java中,客户机和服务器实现的具体方法是什么?它们是怎么运行的?以下面的代码来解释一下……
package test4;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo {
public static void main(String[] args) {
ServerSocket server = null;
Socket clientSocket = null;
String str = null;
DataOutputStream out = null;
DataInputStream in = null;
try {
server = new ServerSocket(4331);
clientSocket = server.accept();
in = new DataInputStream(clientSocket.getInputStream());
out = new DataOutputStream(clientSocket.getOutputStream());
while(true){
str = in.readUTF();//从内存读取
out.writeUTF("hello,我是服务器");//写入内存
out.writeUTF(str);//在将读到的值写入内存
System.out.println("服务器收到:"+str);
Thread.sleep(1000);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}
package test4;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketUtil {
public static void main(String[] args) {
String str =null;
Socket clientSocket;
DataInputStream in ;
DataOutputStream out;
try {
clientSocket = new Socket("localhost",4331);
in = new DataInputStream(clientSocket.getInputStream());
out = new DataOutputStream(clientSocket.getOutputStream());
out.writeUTF("你好");//写入内存
while(true){
str = in.readUTF();//从内存读取数据
out.writeUTF(((int)(Math.random()*10)+1)+"");//写入内存
System.out.println("客户端收到:"+str);
Thread.sleep(1000);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
谢谢高手赐教……
...全文
评论 1
收藏 已收藏
分享
返回顶部
mch20093493
Java 51,407 成员 86,132 内容