Read and Parse US States with Sockets
Sockets, like all other streams, can be read and parsed using stream operations.
Open a connection to a server that contains textual data.
In[1]:=
socket = SocketConnect["http://exampledata.wolfram.com"]
Out[1]=
Write a line containing a GET request for a text file containing all the US states.
In[2]:=
WriteLine[socket, "GET /50states.txt HTTP/1.0 \n"]
Read the first line of the response.
In[3]:=
ReadLine[socket]
Out[3]=
Read all remaining lines.
In[4]:=
output = ReadString[socket];
Inspect the middle of the string to see the start of a newline-delimited list of states.
In[5]:=
StringTake[output, {277, 347}]
Out[5]=
Use SemanticImportString to parse the output, and delete any elements that failed to parse.
In[6]:=
states = DeleteMissing[SemanticImportString[output]]
Out[6]=
Test that indeed all the states were located.
In[7]:=
Equal[Length[states],
Length[EntityList[
EntityClass["AdministrativeDivision", "USStatesAllStates"]]]]
Out[7]=
Close the stream.
In[8]:=
Close[socket]