Skip to content

Commit

Permalink
Merge branch 'master' of github.com:pvcraven/networking_down_under
Browse files Browse the repository at this point in the history
  • Loading branch information
pvcraven committed Mar 28, 2021
2 parents f485a6b + 5cc91f3 commit a21613f
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 27 deletions.
30 changes: 18 additions & 12 deletions ReceiveMultipleMessages.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@
public class ReceiveMultipleMessages {

public static void handleConnection() throws Exception {
// Modify this to match the computer you are connecting to
String ipAddress = "127.0.0.1";
int port = 10000;

// Selector: multiplexor of SelectableChannel objects
Selector channelSelector = Selector.open(); // selector is open here

// ServerSocketChannel: selectable channel for stream-oriented listening sockets
ServerSocketChannel myServerSocketChannel = ServerSocketChannel.open();
InetSocketAddress myAddress = new InetSocketAddress("127.0.0.1", 10000);
InetSocketAddress myAddress = new InetSocketAddress(ipAddress, port);

// Binds the channel's socket to a local address and configures the socket to listen for connections
myServerSocketChannel.bind(myAddress);
Expand Down Expand Up @@ -74,26 +78,28 @@ public static void handleConnection() throws Exception {
} else if (myKey.isReadable()) {

SocketChannel myClient = (SocketChannel) myKey.channel();
ByteBuffer myBuffer = ByteBuffer.allocate(2048);
myClient.read(myBuffer);
String result = new String(myBuffer.array()).trim();
fullMessage = fullMessage + result;

// System.out.println("Message received: " + result);
chunks += 1;
ByteBuffer myBuffer = ByteBuffer.allocate(65536);
int bytesRead = myClient.read(myBuffer);
String result = new String(myBuffer.array());
result = result.substring(0, bytesRead);
if (result.length() > 0) {
fullMessage = fullMessage + result;
chunks += 1;
System.out.println("Message received " + result.length() + " bytes: \"" + result + "\"");
}

if (result.endsWith("Z")) {
if (result.endsWith("\n")) {
myClient.close();
myServerSocketChannel.close();
channelSelector.close();
done = true;
System.out.println("It's time to close connection as we got a Z");
System.out.println("It's time to close connection as we got a \\n");
endTime = System.currentTimeMillis();
}
}
keyIterator.remove();
}
}
myServerSocketChannel.close();
channelSelector.close();
long totalTime = endTime - startTime;
System.out.println("Done receiving " + fullMessage.length() + " in " + chunks + " chunks over " + totalTime + " ms.");
}
Expand Down
31 changes: 18 additions & 13 deletions ReceiveOneShot.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ public void setupSocket() throws Exception {
System.out.println("\nStarting...");

}
public void checkConnection() throws Exception {

public boolean checkConnection() throws Exception {
// Set to true when we have our whole message
boolean done = false;

// Selects a set of keys whose corresponding channels are ready for I/O operations
// For blocking I/O use a select with no data:
Expand Down Expand Up @@ -72,29 +73,33 @@ public void checkConnection() throws Exception {
// Tests whether this key's channel is ready for reading
} else if (myKey.isReadable()) {

SocketChannel myClient = (SocketChannel) myKey.channel();
ByteBuffer myBuffer = ByteBuffer.allocate(2048);
myClient.read(myBuffer);
String result = new String(myBuffer.array()).trim();

System.out.println("Message received: " + result);
SocketChannel myClient = (SocketChannel) myKey.channel();
ByteBuffer myBuffer = ByteBuffer.allocate(65536);
int bytesRead = myClient.read(myBuffer);
String result = new String(myBuffer.array());
result = result.substring(0, bytesRead);
if (result.length() > 0) {
System.out.println("Message received " + result.length() + " bytes: \"" + result + "\"");
}

if (result.endsWith("Z")) {
if (result.endsWith("\n")) {
myClient.close();
myServerSocketChannel.close();
// channelSelector.close();
done = true;
System.out.println("It's time to close connection as we got a Z");
}
}
keyIterator.remove();
}
return done;
}

public static void main(String[] args) throws Exception {
ReceiveOneShot receiveOneShot = new ReceiveOneShot();

receiveOneShot.setupSocket();
while(true)
receiveOneShot.checkConnection();

boolean done = false;
while(!done)
done = receiveOneShot.checkConnection();
}
}
55 changes: 55 additions & 0 deletions SendMultipleMessages.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import java.io.PrintWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class SendMultipleMessages {

private static void sendData(int totalBytes, int messageSizeInBytes)
throws IOException {

// Modify this to match to be THIS computer's address
String ipAddress = "127.0.0.1";
int serverPort = 10000;

InetAddress serverAddress = InetAddress.getByName(ipAddress);
int messagesToSend = totalBytes / messageSizeInBytes;

String myData = "";
for(int i = 0; i < messageSizeInBytes; i++) {
myData += "X";
}

Socket socket = new Socket(serverAddress, serverPort);

// Try changing this to false and see if it changes how packets are sent
boolean autoFlush = true;
PrintWriter out = new PrintWriter(socket.getOutputStream(), autoFlush);

for (int i = 0; i < messagesToSend; i++) {
out.print(myData);
// Try enabling this and see if it changes how packets are sent
// out.flush();
}
out.print("\n");

out.flush();

socket.close();
}
public static void main(String[] args) throws Exception {

// How many bytes to send
int totalBytes = 5000;

// How big each message will be
int messageSizeInBytes = 10;

System.out.println("Sending " + totalBytes + "bytes in " + messageSizeInBytes + " byte chunks.");

// Send the data
sendData(totalBytes, messageSizeInBytes);

System.out.println("Done sending message.");
}
}
7 changes: 5 additions & 2 deletions tcp_send_multiple_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
server_ip_address = '127.0.0.1'
server_ip_port = 10000


def send_data(total_bytes, message_size_in_bytes):
"""
Send a bunch of messages that sum "total_bytes" of data. Break each
Expand All @@ -15,7 +16,7 @@ def send_data(total_bytes, message_size_in_bytes):
# Message as a byte array. (Hence the b at the front.)
# Send byte array with an X: b"X"
# Repeat this (message_size_in_bytes - 1) times.
my_message = b"X" * (message_size_in_bytes)
my_message = b"X" * (message_size_in_bytes - 1)

# Open a socket
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Expand All @@ -36,6 +37,7 @@ def send_data(total_bytes, message_size_in_bytes):

print("Done")


def main():
""" Main program. """

Expand All @@ -47,4 +49,5 @@ def main():
print(f"Sending {total_bytes:,} bytes in {message_size_in_bytes} byte chunks.")
send_data(total_bytes, message_size_in_bytes)

main()

main()

0 comments on commit a21613f

Please sign in to comment.