基本上,作为一项学习任务,我要求创建一个多客户机/服务器应用程序。
在这个类中,我必须创建一个与客户机和服务器一起提供的通信类,在这些类中我将创建一个通信示例,其中客户机或服务器将使用方法“sendmessage”或“receivemessage”来发送/接收消息对象。
客户机/服务器应该不知道通信类使用什么方法。我已经在下面尝试过了,但是我不知道如何从我的客户机/服务器中的通信示例调用这些方法?
我也相信这可能比我用线程做的更容易?如果有人能给我基本的开始代码或解释如何达到它我将非常感激。
谢谢!
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Comms
{
boolean isServer;
public Comms(boolean isServer) throws IOException
{
this.isServer = isServer;
if (isServer == true)
{
ServerSocket socket = new ServerSocket(6000);
try
{
while(true)
{
new ServerConnection(socket.accept());
}
}
catch (IOException e){ e.printStackTrace(); }
finally
{
socket.close();
}
}
else
{
new ClientConnection(new Socket("localhost", 6000));
}
}
class ServerConnection
{
private ObjectInputStream receive;
private ObjectOutputStream send;
private ServerConnection(Socket clientSocket) throws IOException
{
InputStream inputStream = clientSocket.getInputStream();
receive = new ObjectInputStream(inputStream);
OutputStream outputStream = clientSocket.getOutputStream();
send = new ObjectOutputStream(outputStream);
}
public void sendMessage(Message message) throws IOException
{
send.writeObject(message);
}
public Message receiveMessage() throws ClassNotFoundException, IOException
{
Message message = (Message) receive.readObject();
return message;
}
public void closeServerConnection() throws IOException
{
receive.close();
send.close();
}
}
class ClientConnection
{
private ObjectInputStream receive;
private ObjectOutputStream send;
private ClientConnection(Socket socket) throws IOException
{
InputStream inputStream = socket.getInputStream();
receive = new ObjectInputStream(inputStream);
OutputStream outputStream = socket.getOutputStream();
send = new ObjectOutputStream(outputStream);
}
public void sendMessage(Message message) throws IOException
{
send.writeObject(message);
}
public Message receiveMessage() throws ClassNotFoundException, IOException
{
Message message = (Message) receive.readObject();
return message;
}
public void closeClientConnection() throws IOException
{
receive.close();
send.close();
}
}
}
暂无答案!
目前还没有任何答案,快来回答吧!