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]:=
![Click for copyable input](assets.en/read-and-parse-us-states-with-sockets/In_14.png)
socket = SocketConnect["http://exampledata.wolfram.com"]
Out[1]=
![](assets.en/read-and-parse-us-states-with-sockets/O_12.png)
Write a line containing a GET request for a text file containing all the US states.
In[2]:=
![Click for copyable input](assets.en/read-and-parse-us-states-with-sockets/In_15.png)
WriteLine[socket, "GET /50states.txt HTTP/1.0 \n"]
Read the first line of the response.
In[3]:=
![Click for copyable input](assets.en/read-and-parse-us-states-with-sockets/In_16.png)
ReadLine[socket]
Out[3]=
![](assets.en/read-and-parse-us-states-with-sockets/O_13.png)
Read all remaining lines.
In[4]:=
![Click for copyable input](assets.en/read-and-parse-us-states-with-sockets/In_17.png)
output = ReadString[socket];
Inspect the middle of the string to see the start of a newline-delimited list of states.
In[5]:=
![Click for copyable input](assets.en/read-and-parse-us-states-with-sockets/In_18.png)
StringTake[output, {277, 347}]
Out[5]=
![](assets.en/read-and-parse-us-states-with-sockets/O_14.png)
Use SemanticImportString to parse the output, and delete any elements that failed to parse.
In[6]:=
![Click for copyable input](assets.en/read-and-parse-us-states-with-sockets/In_19.png)
states = DeleteMissing[SemanticImportString[output]]
Out[6]=
![](assets.en/read-and-parse-us-states-with-sockets/O_15.png)
Test that indeed all the states were located.
In[7]:=
![Click for copyable input](assets.en/read-and-parse-us-states-with-sockets/In_20.png)
Equal[Length[states],
Length[EntityList[
EntityClass["AdministrativeDivision", "USStatesAllStates"]]]]
Out[7]=
![](assets.en/read-and-parse-us-states-with-sockets/O_16.png)
Close the stream.
In[8]:=
![Click for copyable input](assets.en/read-and-parse-us-states-with-sockets/In_21.png)
Close[socket]