C # socket Entry 1

Source: Internet
Author: User

1. ServerProgram

1 Using System;
2 Using System. Collections. Generic;
3 Using System. text;
4 Using System. net. Sockets;
5 Using System. net;
6
7 Namespace Leleapplication1
8 {
9 Class Program
10 {
11 Static   Void Main ( String [] ARGs)
12 {
13 // 1. Create a set of characters
14 Socket slisten =   New Socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
15
16 // 2. Fill in the IP address
17 IPaddress IP = IPaddress. parse ( " 127.0.0.1 " );
18 Ipendpoint IPE =   New Ipendpoint (IP, 4321 );
19
20 // 3. Bind
21 Slisten. BIND (IPE );
22
23 // 4. Listening
24 Slisten. Listen ( 2 );
25
26 // 5. Receive customer connection requests cyclically
27 While ( True )
28 {
29 Socket clientsocket;
30 Try
31 {
32 Clientsocket = Slisten. Accept ();
33 }
34 Catch
35 {
36 Throw ;
37 }
38 // Send data to the client
39 Clientsocket. Send (encoding. Unicode. getbytes ( " Hello !!!! " ));
40 }
41 }
42
43 }
44 }
45

Complete, server,

2. Check the client now.

1 Using System;
2 Using System. Collections. Generic;
3 Using System. text;
4 Using System. net. Sockets;
5 Using System. net;
6
7 Namespace Leleapplication2
8 {
9 Class Program
10 {
11 Static   Void Main ( String [] ARGs)
12 {
13 // 1. Create a set of characters
14 Socket s =   New Socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
15
16 // 2. Enter the remote IP address.
17 IPaddress IP = IPaddress. parse ( " 127.0.0.1 " );
18 Ipendpoint IPE =   New Ipendpoint (IP, 4321 );
19
20 //3. Connect to the server 21 Console. writeline ("Start connecting to the server ....");
22 S. Connect (IPE );
23
24 // 4. receive data
25 Byte [] Buffer =   New   Byte [ 1024 ];
26 S. Receive (buffer, buffer. length, socketflags. None );
27 VaR msg = Encoding. Unicode. getstring (buffer );
28 Console. writeline ( " Receive message: {0} " , MSG );
29
30 Console. readkey ();
31 }
32 }
33 }

Okay. Check the effect ~~

Simple ~~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.