Skip to content

Instantly share code, notes, and snippets.

@harrisonhjones
Created November 21, 2014 01:29
Show Gist options
  • Save harrisonhjones/bf43288b8a1df2f22a9f to your computer and use it in GitHub Desktop.
Save harrisonhjones/bf43288b8a1df2f22a9f to your computer and use it in GitHub Desktop.
JavaToSparkCore
/* Includes ------------------------------------------------------------------*/
#include "application.h"
TCPClient client;
byte server[] = { 10, 0, 0, 40 }; // PUT YOUR SERVER'S IP HERE!
void setup()
{
// Make sure your Serial Terminal app is closed before powering your Core
Serial.begin(9600);
// Now open your Serial Terminal, and hit any key to continue!
while(!Serial.available()) SPARK_WLAN_Loop();
Serial.println("connecting...");
if (client.connect(server, 6000))
{
Serial.println("connected");
client.println("Hello from the SparkCore!");
}
else
{
Serial.println("connection failed");
}
}
void loop()
{
if (client.available())
{
char c = client.read();
Serial.print(c);
}
if (!client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;) SPARK_WLAN_Loop();
}
}
package simplejavaserver;
import java.net.*;
import java.io.*;
public class SimpleJavaServer extends Thread
{
private ServerSocket serverSocket;
public SimpleJavaServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
//serverSocket.setSoTimeout(10000); // By commenting out the timeout the server will wait for the client forever!
}
public void run()
{
while(true)
{
try
{
// Let the user know we are waiting for a client
System.out.println("Waiting for client on " +
Inet4Address.getLocalHost().getHostAddress() + ":" +
serverSocket.getLocalPort() + "...");
// Wait for a new client. Hang until a new one connects
Socket server = serverSocket.accept();
//DataInputStream in = new DataInputStream(server.getInputStream());
BufferedReader din = new BufferedReader(new InputStreamReader(server.getInputStream()));
DataOutputStream out = new DataOutputStream(server.getOutputStream());
// Let the user know we have accepted a client
System.out.println("Just connected to " + server.getRemoteSocketAddress());
// Let the user know what the client sent
System.out.print("Client: ");
System.out.println(din.readLine());
// Send the welcome message to the client
System.out.println("Sending welcome messsage");
out.writeChars("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");
// Close the connection the client so we can listen for new cients
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = 6000;
try
{
Thread t = new SimpleJavaServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment