Setting a socket

Would you mind using this example for your java code: (from: http://www.tutorialspoint.com/java/java_networking.htm)

// File Name GreetingServer.java

import java.net.*;
import java.io.*;

public class GreetingServer extends Thread
{
    private ServerSocket serverSocket;

    public GreetingServer(int port) throws IOException
    {
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(10000);
    }

    public void run()
    {
        while(true)
        {
            try
            {
                System.out.println("Waiting for client on port " +
                serverSocket.getLocalPort() + "...");
                Socket server = serverSocket.accept();
                System.out.println("Just connected to "
                + server.getRemoteSocketAddress());
                DataInputStream in =
                new DataInputStream(server.getInputStream());
                System.out.println(in.readUTF());
                DataOutputStream out =
                new DataOutputStream(server.getOutputStream());
                out.writeUTF("Thank you for connecting to "
                + server.getLocalSocketAddress() + "\nGoodbye!");
                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 GreetingServer(port);
            t.start();
        }catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

That should setup a Java Server on Port 6000. Run the server code. It should wait for incoming connection. Next flash your SparkCore will the following code (modify the IP for you server’s ip)

// SYNTAX
TCPClient client;
// EXAMPLE USAGE

TCPClient client;
byte server[] = { 74, 125, 224, 72 }; // 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();
  }
}

Open up the serial console on you computer and connect to your SparkCore. Press anykey and look for output.

Let me know if you have any issues.

1 Like