Browse Source

Wrote a bit of code for the protocol

proto
Thomas Johnson 3 years ago
parent
commit
fcf37d8214
  1. 9
      proto/ProtoHandler.java
  2. 27
      proto/ProtoID.java
  3. 48
      proto/ProtoIn.java
  4. 25
      proto/ProtoOut.java

9
proto/ProtoHandler.java

@ -0,0 +1,9 @@
package proto;
public interface ProtoHandler
{
void handleJoin(String username);
void handlePart(String username);
void handleListing(String names[]);
void handleUnknownCommand(byte id);
}

27
proto/ProtoID.java

@ -0,0 +1,27 @@
package proto;
// This file is mo
// As agreed upon when designing the protocol
public enum ProtoID
{
ERROR((byte) 0),
JOIN((byte) 1),
PART((byte) 2),
LISTING((byte) 3),
MESSAGE((byte) 4),
FILE((byte) 5),
INFO((byte) 6);
private byte b;
ProtoID(byte b)
{
this.b = b;
}
public byte b()
{
return b;
}
}

48
proto/ProtoIn.java

@ -0,0 +1,48 @@
package proto;
import java.io.DataInputStream;
import java.nio.charset.Charset;
public class ProtoIn
{
private DataInputStream dis;
public boolean loop;
private ProtoHandler handler;
public ProtoIn(DataInputStream dis, ProtoHandler handler)
{
this.dis = dis;
this.handler = handler;
}
private String readname() throws java.io.IOException
{
byte length = dis.readByte();
byte[] bytes = {};
dis.read(bytes, 0, length);
return new String(bytes, Charset.forName("UTF-8"));
}
void mainLoop()
{
while (this.loop)
{
try {
byte id = dis.readByte();
int length = dis.readInt();
switch (id)
{
case 3:
short nlen = dis.readShort();
String username = readname();
break;
default:
Thread t = new Thread(() -> handler.handleUnknownCommand(id));
t.start();
}
} catch (Exception e) {} // Not much we can do about this
}
}
}

25
proto/ProtoOut.java

@ -0,0 +1,25 @@
package proto;
import java.io.DataOutputStream;
import java.io.IOException;
public class ProtoOut
{
private DataOutputStream out;
public ProtoOut(DataOutputStream out)
{
this.out = out;
}
public void requestUserList(String username) throws IOException
{
if (username.length() > 127)
throw new IOException("Username too long");
out.writeByte(3);
out.writeShort(0);
out.writeByte((byte) username.length());
out.writeUTF(username);
out.flush();
}
}
Loading…
Cancel
Save