50,545
社区成员
发帖
与我相关
我的任务
分享
public class ServerDemo {
public static void main(String[] args) {
ServerSocket server = null; //声明ServerSocket对象
Socket clientSocket = null;//声明一个Socket对象表示客户端
String str = null;
DataOutputStream out = null; //输出流
DataInputStream in = null;//输入流
try {
server = new ServerSocket(4331);//此服务器在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();
}
}
}
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();
}
}
}