2D游戏套接字服务器和客户端

时间:2016-03-22 22:42:05

标签: java swing sockets

嘿伙计们我正在尝试使用套接字来实现我正在开始的游戏的多人游戏方面。我使用我发现的一些教程创建了代码。我理解基本概念,但是在尝试想办法让两个独立的玩家,并将所有数据发送到客户端和服务器时,我很难。

这是我创建的测试服务器类(只发送一个字符串):

package Server;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public void Start() throws IOException{
        String clientSentence;
        ServerSocket socket = new ServerSocket(8877);

        while(true){
            Socket connectionSocket = socket.accept();
            BufferedReader fromClient = 
                    new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream toClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = fromClient.readLine();
            System.out.println("MSG from client: " + clientSentence);
            toClient.writeBytes("Sending back: "+ clientSentence);
            socket.close();
            fromClient.close();
            toClient.close();
        }
    }
}

这是客户端代码:

package Client;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class Client {

    public void Start() throws Exception{
        String sentence;
        String modified;
        BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
        Socket clientSocket = new Socket("localhost", 8877);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        sentence = fromUser.readLine();
        outToServer.writeBytes(sentence);
        modified = inFromServer.readLine();
        System.out.println("From Server: " + modified);
        clientSocket.close();
    }
}

我会将数据作为对象发送吗?或者我会将每个变量分别作为整数值发送?

谢谢!

0 个答案:

没有答案