program.cs

来自「基于symbian和C#程序进行socket通信的代码」· CS 代码 · 共 48 行

CS
48
字号
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using System.IO;

namespace TestSocketConsole {
	class Program {
		static void Main(string[] args) {

			// 创建套接字
			Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

			// 本地绑定地址
			IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8532);
			socket.Bind(ep);
			socket.Listen(20);

			while (true) {
				Socket newSocket = socket.Accept();
				IPEndPoint remoteEp = (IPEndPoint)newSocket.RemoteEndPoint;
				Console.WriteLine(remoteEp.Address.ToString() + ":" + remoteEp.Port);

				Thread thread = new Thread(new ParameterizedThreadStart(
					delegate(object acceptSocketObject) {
						try {
							Socket acceptSocket = (Socket)acceptSocketObject;
							byte[] content = new byte[8];

							// 一次性接收8个字节  不管超出的部分
							acceptSocket.Receive(content);

							Console.WriteLine(Encoding.ASCII.GetString(content));

							// 返回次8个字节
							acceptSocket.Send(content);
						}
						catch { }
					}));

				thread.Start(newSocket);
			}
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?