This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revision | |||
user:mtaft4:portfolio:providerclass [2011/03/22 15:11] – mtaft4 | user:mtaft4:portfolio:providerclass [2011/03/22 15:18] (current) – mtaft4 | ||
---|---|---|---|
Line 1: | Line 1: | ||
+ | This is code for a Java based server to send a series of predefined messages back and forth before shutting down. The comments will contain sort of beginning how this works comments to help people from the class understand the code. | ||
+ | <code java> | ||
+ | import java.net.ServerSocket; | ||
+ | public class Provider{ | ||
+ | ServerSocket providerSocket; | ||
+ | Socket connection = null; //No connection yet | ||
+ | ObjectOutputStream toClient; | ||
+ | ObjectInputStream fromClient; | ||
+ | String message; | ||
+ | Provider(){} | ||
+ | void run() { //Method for actually creating sockets and sending messages | ||
+ | try { | ||
+ | providerSocket = new ServerSocket(2004, | ||
+ | System.out.println(" | ||
+ | connection = providerSocket.accept(); | ||
+ | System.out.println(" | ||
+ | toClient = new ObjectOutputStream(connection.getOutputStream()); | ||
+ | toClient.flush(); | ||
+ | in = new ObjectInputStream(connection.getInputStream()); | ||
+ | sendMessage(" | ||
+ | do { //loop while there' | ||
+ | try { //do the messaging | ||
+ | message = (String)in.readObject(); | ||
+ | System.out.println(" | ||
+ | if (message.equals(" | ||
+ | sendMessage(" | ||
+ | } | ||
+ | catch(ClassNotFoundException classnot) { //catch the exceptions that the try can throw | ||
+ | System.err.println(" | ||
+ | } | ||
+ | } while (!message.equals(" | ||
+ | } | ||
+ | catch(IOException ioException) { //catch exceptions | ||
+ | ioException.printStackTrace(); | ||
+ | } | ||
+ | finally { | ||
+ | try { //close all connections | ||
+ | in.close(); | ||
+ | out.close(); | ||
+ | providerSocket.close(); | ||
+ | } | ||
+ | catch(IOException ioException) { | ||
+ | ioException.printStackTrace(); | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | void sendMessage(String msg) { //sending messages to the client | ||
+ | try { | ||
+ | out.writeObject(msg); | ||
+ | out.flush(); | ||
+ | System.out.println(" | ||
+ | } | ||
+ | catch(IOException ioException) { | ||
+ | ioException.printStackTrace(); | ||
+ | } | ||
+ | } | ||
+ | public static void main(String args[]) { //Static method to instantiate the class we created | ||
+ | Provider server = new Provider(); | ||
+ | while(true) { | ||
+ | server.run(); | ||
+ | } | ||
+ | } | ||
+ | }</ | ||
+ | |||
+ | The code is a little choppy currently as this was written with limited knowledge of Java and pretty much straight from the Java documentation. The next step is to either get this to send user defined messages or to send midi notes back and forth. Hopefully a it stands the client/ |