[Windows 8]使用Socket連接-----建立客戶端(上)

[Windows 8]使用Socket連接-----建立客戶端(上)

 

首先,新增一個【StreamSocketExample】的Windows 空白應用程式

然後開啟【MainPage.xaml】輸入以下程式碼:


  <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock HorizontalAlignment="Left" Margin="257,131,0,0" TextWrapping="Wrap" Text="IP地址:" FontSize="50" VerticalAlignment="Top"/>
        
        <TextBox x:Name="HostName" HorizontalAlignment="Left" Margin="591,112,0,0" TextWrapping="Wrap" Width="500" Text="localhost" FontSize="50" VerticalAlignment="Top"/>
        
        <TextBlock HorizontalAlignment="Left" Margin="248,251,0,0" TextWrapping="Wrap" Text="埠號碼:" FontSize="50" VerticalAlignment="Top"/>
        
        <TextBox x:Name="ServerPort" FontSize="50" Width="500" HorizontalAlignment="Left" Margin="591,232,0,0" TextWrapping="Wrap" Text="9900" VerticalAlignment="Top"/>
        
        <TextBlock FontSize="40" x:Name="LogInfo" HorizontalAlignment="Left" Margin="591,363,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Height="65" Width="500" ></TextBlock>
        
        <TextBox Name="Message" HorizontalAlignment="Left" FontSize="40" Margin="591,494,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="74" Width="500"></TextBox>
        
        <TextBox Name="ShowMessage" HorizontalAlignment="Left" FontSize="40" Margin="591,607,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="108" Width="500"></TextBox>
        
        <Button Click="ConnectServer_Click" Content="連接" FontSize="50" HorizontalAlignment="Left" Margin="248,348,0,0" VerticalAlignment="Top" Height="80" Width="141"/>
        
        <Button Click="Close_Click" Content="關閉" FontSize="50" HorizontalAlignment="Left" Margin="416,348,0,0" VerticalAlignment="Top" Height="80" Width="135"/>
        
        <Button Click="SendMessage_Click" Content="發送消息" FontSize="40" HorizontalAlignment="Left" Margin="257,494,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.556,2.287" Height="75" Width="294"/>

    </Grid>

上面的程式碼中,新增了四個 TextBox 控制項和三個 Button 按鈕

四個 TextBox 控制項,一個用來輸入服務器IP位址,一個用來輸入服務器的埠號碼

另外兩個,一個是用輸入發送訊息,一個是用來回應訊息

"連接" 按鈕是用來建立與服務器間的連接

"關閉" 按鈕是實現關閉連接的功能

"發送訊息" 是用來向服務器發送訊息

前台的設計畫面如下:

377

 

關於後台的執行,請繼續參考下篇:

[Windows 8]使用Socket連接-----建立客戶端(下)