Skip to content
Snippets Groups Projects
Commit 37097b38 authored by Brutzman, Don's avatar Brutzman, Don
Browse files

delete extraneous directory

parent 908cf9be
No related branches found
No related tags found
No related merge requests found
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.Socket;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author justi
*/
public class FrankClient {
/**
*/
public final static String LOCALHOST = "0:0:0:0:0:0:0:1";
/**
* Program invocation, execution starts here
* @param args command-line arguments
* @throws java.lang.InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// Local variables/fields
Socket socket = null;
InputStream is;
Reader isr;
BufferedReader br;
String serverMessage;
int clientLoopCount = 0;
try {
while (true)
{
clientLoopCount++; // increment at beginning of loop for reliability
System.out.println(FrankClient.class.getName() + " creating socket...");
// We request an IP to connect to ("localhost") and
// port number at that IP (2317). This establishes
// a connection to that IP in the form of a Socket
// object; the server uses a ServerSocket to wait for
// connections.
socket = new Socket(LOCALHOST, 2318); // locohost?
// Now hook everything up (i.e. set up the streams), Java style:
is = socket.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
// Read a single line written by the server. We'd
// do things a bit differently if there were many lines to be read
// from the server instead of one only.
serverMessage = br.readLine();
System.out.println("==================================================");
System.out.print ("Client loop " + clientLoopCount + ": ");
System.out.println("now we're talking!");
System.out.println("The message the server sent was: '" + serverMessage + "'");
// socket gets closed, either automatically/silently by this code (or possibly by the server)
Thread.sleep(500l); // slow things down, for example 500l (long) = 500 msec
} // end while(true) // infinite loops are dangerous, be sure to kill this process!
}
catch (IOException e)
{
System.err.println("Problem with " + FrankClient.class.getName() + " networking:"); // describe what is happening
System.err.println("Error: " + e);
// Provide more helpful information to user if exception occurs due to running twice at one time
if (e instanceof java.net.BindException) {
System.err.println("*** Be sure to stop any other running instances of programs using this port!");
}
}
finally // occurs after any other activity when shutting down
{
try {
if (socket != null)
socket.close();
} catch (IOException e) {}
// program exit: tell somebody about that happening. Likely cause: server drops connection.
System.out.println();
System.out.println( "FrankClient.class.getName() + exit");
}
}
}
import java.io.*;
import java.net.*;
/**
* Very slightly more complex than example1, further modifying example2. The
* only thing this does differently is introduce a loop into the response, so
* you don't have to restart the program after one response. Also, it prints out
* the socket pair the server sees. Run the program via telnet several times and
* compare the socket pairs.
*
* telnet (nc) localhost 2318
*
* If you're sophisticated you can contact the instructor's computer while
* running this program.
*
* telnet (nc) [ipNumberOfServerLaptop] 2317
*
* and have the instructor display the socket pairs received.
*
* @author mcgredo
* @author brutzman
*/
public class FrankServer {
/**
* Program invocation, execution starts here
* If already compiled, can run using console in directory ../../build/classes/ by invoking \
* java -classpath . TcpExamples.TcpExample3Server
* @param args command-line arguments
*/
public static void main(String[] args) {
try {
// ServerSocket waits for a connection from a client.
// Notice that it is outside the loop; ServerSocket
// needs to be made only once.
System.out.println(FrankServer.class.getName() + " has started..."); // it helps debugging to put this on console first
ServerSocket serverSocket = new ServerSocket(2318);
OutputStream os;
PrintStream ps;
InetAddress localAddress, remoteAddress;
int localPort, remotePort;
int serverLoopCount = 0;
// Server is up and waiting (i.e. "blocked" or paused)
// Loop, infinitely, waiting for client connections.
// Stop the program somewhere else.
while (true) {
// block until connected to a client
try (Socket clientConnectionSocket = serverSocket.accept())
{
serverLoopCount++; // increment at beginning of loop for reliability
// Now hook everything up (i.e. set up the streams), Java style:
os = clientConnectionSocket.getOutputStream();
ps = new PrintStream(os);
ps.println("This is response " + serverLoopCount + " produced by the server."); // this gets sent back to client!
// Print some information locally about the Socket connection.
// This includes the port and IP numbers on both sides (the socket pair).
localAddress = clientConnectionSocket.getLocalAddress();
remoteAddress = clientConnectionSocket.getInetAddress();
localPort = clientConnectionSocket.getLocalPort();
remotePort = clientConnectionSocket.getPort();
System.out.print ("Server loop " + serverLoopCount + ": ");
// My socket pair connection looks like this, to localhost:
// Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54876 ))
// Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54881 ))
// Why is the first IP/port the same, while the second set has different ports?
System.out.println(FrankServer.class.getName() + " socket pair showing host name, address, port:");
System.out.println(" (( " +
localAddress.getHostName() + "=" + localAddress.getHostAddress() + ", " + localPort + " ), ( " +
remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " ))");
if ( localAddress.getHostName().equals( localAddress.getHostAddress()) ||
remoteAddress.getHostName().equals(remoteAddress.getHostAddress()))
System.out.println(" note HostName matches address if host has no DNS name");
// Not/*i*/ce the use of flush() and try w/ resources. Without
// the try w/ resources the Socket object may stay open for
// a while after the client has stopped needing this
// connection. try w/ resources explicitly ends the connection.
ps.flush();
// like it or not, you're outta here!
}
}
} catch (IOException e) {
System.err.println("Problem with " + FrankServer.class.getName() + " networking: " + e);
// Provide more helpful information to user if exception occurs due to running twice at one time
if (e instanceof java.net.BindException) {
System.err.println("*** Be sure to stop any other running instances of programs using this port!");
}
}
}
}
package MV3500Cohort2021JulySeptember.homework1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.Socket;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author justi
*/
public class FrankTCPExample3Client {
/**
*/
public final static String LOCALHOST = "0:0:0:0:0:0:0:1";
/**
* Program invocation, execution starts here
* @param args command-line arguments
* @throws java.lang.InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// Local variables/fields
Socket socket = null;
InputStream is;
Reader isr;
BufferedReader br;
String serverMessage;
int clientLoopCount = 0;
try {
while (true)
{
clientLoopCount++; // increment at beginning of loop for reliability
System.out.println(FrankTCPExample3Client.class.getName() + " creating socket...");
// We request an IP to connect to ("localhost") and
// port number at that IP (2317). This establishes
// a connection to that IP in the form of a Socket
// object; the server uses a ServerSocket to wait for
// connections.
socket = new Socket(LOCALHOST, 2318); // locohost?
// Now hook everything up (i.e. set up the streams), Java style:
is = socket.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
// Read a single line written by the server. We'd
// do things a bit differently if there were many lines to be read
// from the server instead of one only.
serverMessage = br.readLine();
System.out.println("==================================================");
System.out.print ("Client loop " + clientLoopCount + ": ");
System.out.println("now we're talking!");
System.out.println("The message the server sent was: '" + serverMessage + "'");
// socket gets closed, either automatically/silently by this code (or possibly by the server)
Thread.sleep(500l); // slow things down, for example 500l (long) = 500 msec
} // end while(true) // infinite loops are dangerous, be sure to kill this process!
}
catch (IOException e)
{
System.err.println("Problem with " + FrankTCPExample3Client.class.getName() + " networking:"); // describe what is happening
System.err.println("Error: " + e);
// Provide more helpful information to user if exception occurs due to running twice at one time
if (e instanceof java.net.BindException) {
System.err.println("*** Be sure to stop any other running instances of programs using this port!");
}
}
finally // occurs after any other activity when shutting down
{
try {
if (socket != null)
socket.close();
} catch (IOException e) {}
// program exit: tell somebody about that happening. Likely cause: server drops connection.
System.out.println();
System.out.println( "FrankTCPExample3Client.class.getName() + exit");
}
}
}
#Adapted from https://github.com/realpython/materials/blob/master/multiconn-client.py
import sys
import socket
import selectors
import types
import contextlib
import os
with contextlib.suppress(FileNotFoundError):
os.remove('screenshot.png')
sel = selectors.DefaultSelector()
def start_connections(host, port, x3d_id):
server_addr = (host, port)
print("starting connection to", server_addr)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(False)
sock.connect_ex(server_addr)
events = selectors.EVENT_READ | selectors.EVENT_WRITE
data = types.SimpleNamespace(
connid=1,
msg_total=sum([1]),
recv_total=0,
messages=[str(x3d_id).encode()],
outb=b"",
)
sel.register(sock, events, data=data)
def service_connection(key, mask):
sock = key.fileobj
data = key.data
if mask & selectors.EVENT_READ:
recv_data = sock.recv(1024) # Should be ready to read
sock.settimeout(None)
if not recv_data:
print("closing connection", data.connid)
sel.unregister(sock)
sock.close()
if recv_data:
with open('screenshot.png','ab') as b:
b.write(recv_data)
data.recv_total += len(recv_data)
print("received " + str(data.recv_total) + " image bytes from connection", data.connid)
if mask & selectors.EVENT_WRITE:
if not data.outb and data.messages:
data.outb = data.messages.pop(0)
if data.outb:
print("sending", repr(data.outb), "to connection", data.connid)
sent = sock.send(data.outb) # Should be ready to write
data.outb = data.outb[sent:]
if len(sys.argv) != 4:
print("This program simulates the agent communicate process where a client requests a dynamically rendered X3D asset from the host.")
print("usage:", sys.argv[0], "<host 192.168.86.225> <port 65500> <x3d asset number [0-14138] >")
sys.exit(1)
host, port, x3d_id = sys.argv[1:4]
start_connections(host, int(port), int(x3d_id))
try:
while True:
events = sel.select(timeout=1)
if events:
for key, mask in events:
service_connection(key, mask)
# Check for a socket being monitored to continue.
if not sel.get_map():
break
except KeyboardInterrupt:
print("caught keyboard interrupt, exiting")
finally:
sel.close()
sel.close()
\ No newline at end of file
MV3500Cohort2021JulySeptember/homework1/Lentz_Python/sequence.png

73.6 KiB

#Adapted from https://github.com/realpython/materials/blob/master/multiconn-client.py
import sys
import socket
import selectors
import types
import subprocess
import time
sel = selectors.DefaultSelector()
def accept_wrapper(sock):
conn, addr = sock.accept() # Should be ready to read
print("accepted connection from", addr)
conn.setblocking(False)
data = types.SimpleNamespace(addr=addr, inb=b"", outb=b"")
events = selectors.EVENT_READ | selectors.EVENT_WRITE
sel.register(conn, events, data=data)
def service_connection(key, mask):
sock = key.fileobj
data = key.data
if mask & selectors.EVENT_READ:
recv_data = sock.recv(1024) # Should be ready to read
if recv_data:
data.outb += recv_data
else:
print("closing connection to", data.addr)
sel.unregister(sock)
sock.close()
if mask & selectors.EVENT_WRITE:
if data.outb:
fn = data.outb.decode('ascii')+'.x3d'
print( "getting " + fn )
subprocess.run(["wget", "https://nps.edu/x3d_repository/"+fn,"-O","x3d.x3d"])
subprocess.run(["/castle_game_engine/bin/view3dscene", "--screenshot","0","screenshot.png","x3d.x3d"])
png_bytes = open('screenshot.png','rb').read()
print("sending png of length " + str(len(png_bytes)) + ' to ', data.addr)
sent = sock.send(png_bytes) # Should be ready to write
data.outb = png_bytes[sent:]
#time.sleep(5)
#subprocess.run(["rm", "screenshot.png","x3d.x3d"])
if len(sys.argv) != 3:
print("usage:", sys.argv[0], "<host> <port>")
sys.exit(1)
host, port = sys.argv[1], int(sys.argv[2])
lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
lsock.bind((host, port))
lsock.listen()
print("listening on", (host, port))
lsock.setblocking(False)
sel.register(lsock, selectors.EVENT_READ, data=None)
try:
while True:
events = sel.select(timeout=None)
for key, mask in events:
if key.data is None:
accept_wrapper(key.fileobj)
else:
service_connection(key, mask)
except KeyboardInterrupt:
print("caught keyboard interrupt, exiting")
finally:
sel.close()
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment