java - 如何在套接字编程中将我的课程放在客户端中?
问题描述
我使用 JavaFX 制作了一个类似于 Flappy Bird 的游戏。现在我想通过使用 localhost IP 来播放它。如何将 FlappyBird 中的类移动到客户端,以便 Flappybird 成为客户端?
还有我们如何让多个客户使用它?这段代码是我用简单的概念制作的一个简单的代码,但我不明白的是如何在套接字编程中制作一个类,就像在一个小鸟游戏中一样。我如何实现从飞扬的鸟到客户端的所有内容,以便客户端成为飞扬的鸟对象
客户:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class FlappyClient
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public FlappyClient(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
//=============
// close the connection
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
FlappyClient client = new FlappyClient("localhost", 5000);
}
}
````````````````````````````````````````````````
````````````````````````````````````````````````
public class FlappyServer
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public FlappyServer(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
FlappyServer server = new FlappyServer(5000);
}
}
`````````````````````````````````````````````
**The flappy bird class is too big. Lets call it FlappyBird I want to make this flappybird a client for the server**
解决方案
我找到了答案
Main.main(null);
推荐阅读
- google-apps-script - 您如何获取 GAS 项目中各个脚本的 ID?
- java - CloudFunction 作为 gradle 子项目
- javascript - 为什么等待服务器响应后不执行代码行
- python - 'TypeError:在尝试模拟异常时不允许捕获不从 BaseException 继承的类'
- python - 如何在 python 中调用使用命令行界面的 Web 服务?
- javascript - 如何使用 JavaScript 查找一个字符是否在字符串中多次出现?
- c - 如果存在等于给定数字的数字组合,则打印
- macos - macOS 上的终端/iTerm2 窗口名称:如何取消 SSH 以显示下一个进程?
- javascript - 将对象传播到参数中?
- algorithm - 将椭圆弧拟合到点或其他曲线