Wolfram Language

Systems-Level Functionality

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
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]:=
Click for copyable input
WriteLine[socket, "GET /50states.txt HTTP/1.0 \n"]

Read the first line of the response.

In[3]:=
Click for copyable input
ReadLine[socket]
Out[3]=

Read all remaining lines.

In[4]:=
Click for copyable input
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
StringTake[output, {277, 347}]
Out[5]=

Use SemanticImportString to parse the output, and delete any elements that failed to parse.

In[6]:=
Click for copyable input
states = DeleteMissing[SemanticImportString[output]]
Out[6]=

Test that indeed all the states were located.

In[7]:=
Click for copyable input
Equal[Length[states], Length[EntityList[ EntityClass["AdministrativeDivision", "USStatesAllStates"]]]]
Out[7]=

Close the stream.

In[8]:=
Click for copyable input
Close[socket]

Related Examples

de es fr ja ko pt-br ru zh