Параллельная работа сокетов в C#. Потоки в C# using System; using System.Threading; public class ThreadExample { public static void ThreadProc() { for.

Slides:



Advertisements
Similar presentations
Continuation of chapter 6…. Nested while loop A while loop used within another while loop is called nested while loop. Q. An illustration to generate.
Advertisements

Multiplexing/Demux. CPSC Transport Layer 3-2 Multiplexing/demultiplexing application transport network link physical P1 application transport network.
SWE 344 Internet Protocols & Client Server Programming The C# Sockets Helper Classes.
System Programming Practical Session 5 Liveness, Guarded Methods, and Thread Timing.
Group Communication using Ensemble. 2 Group Communication - Overview Group Communication as a middleware, providing an application with: Group membership.
System Programming Practical session 11 Multiple clients server Non-Blocking I/O.
MS.Net Framework with emphasis on online gaming Ed Mucker CS522 9 Dec 02.
TCP Socket Programming CPSC 441 Department of Computer Science University of Calgary.
Network Programming and Java Sockets 1 Dr. Christian Vecchiola Postdoctoral Research Fellow Cloud Computing and Distributed Systems.
Socket Communication in C#
1 The Warehouse Program. 2 A console program. Listens for connect requests from the call center program. Accepts connection. Reads message. Order ID Prints.
Multithreading.
Programming Handheld and Mobile devices 1 Programming of Handheld and Mobile Devices Lecture 19 Microsoft’s Approach 1 –.NET Mobile Framework part 2 Rob.
NAVY Research Group Department of Computer Science Faculty of Electrical Engineering and Computer Science VŠB-TUO 17. listopadu Ostrava-Poruba.
 2002 Prentice Hall. All rights reserved. 1 Chapter 22 – Networking: Streams- Based Sockets and Datagrams Outline 22.1 Introduction 22.2 Establishing.
 2002 Prentice Hall. All rights reserved. 1 Chapter 22 – Networking: Streams- Based Sockets and Datagrams Outline 22.1Introduction 22.2 Establishing a.
Network Layer Programing Connection-Oriented Sockets SWE 344 Internet Protocols & Client Server Programming.
.NET & C# Introduction 11 March, 2004 Yusung Kim CS441 Introduction to Computer Networking.
Chapter 13 Working with Threads. Copyright 2006 Thomas P. Skinner2 Other Reference The book Programming Microsoft.NET by Jeff Prosise. Chapter 14 is excellent.
Lector: Aliyev H.U. Lecture №5 Telecommunication network software design with.NET. Using streams for network programming TASHKENT UNIVERSITY OF INFORMATION.
Lector: Aliyev H.U. Lecture №6 Design of client-server communication software. TCP-based network programming TASHKENT UNIVERSITY OF INFORMATION TECHNOLOGIES.
Windows Programming Using C# Internet Programming.
Internet Applications and Network Programming Dr. Abraham Professor UTPA.
Özgür Zeytinci Network Programming Microsoft.NET.
10/17/2015Vimal1 Threads By 10/17/2015Vimal2 Why use threads?? It is a powerful programming tool Computer users take it for granted.
Lecture 16: Multithreaded Programming. public partial class Form1 : Form { Thread ct; Thread rt; public static int circle_sleep = 0; public static int.
Lector: Aliyev H.U. Lecture №11: FTP based file communication software design. Communicating with File Servers TASHKENT UNIVERSITY OF INFORMATION TECHNOLOGIES.
1 Web Based Programming Section 8 James King 12 August 2003.
Multi-Client/Server GUI Application. Overview As part of the TCP.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
UDP Client-Server. The Socket Class The Socket class provides a set of methods and properties for network communications. The Socket class allows you.
Клиент-сервер: обмен данными Лабораторная работа 4.
Network Programming with C# Exceed Camp #2, CPE, KU Day 3.
Connectionless Sockets SWE 344 Internet Protocols & Client Server Programming.
Threads & Networking C# offers facilities for multi threading and network programming an application roughly corresponds to a process, handled by the OS.
Using Threads SWE 344 Internet Protocols & Client Server Programming.
12/5/2015.net 1 system.net Contains any network functionallity you would need in c# Several sub namespaces exists to allow for more fined control –System.Net.Sockets.
Programming Handheld and Mobile devices 1 Programming of Handheld and Mobile Devices Lecture 18 Microsoft’s Approach 1 –.NET Mobile Framework part 2 Rob.
1 Tips & Tricks: Using System.Net To Write Better Connected Applications Durgaprasad Gorti COML02 Test Lead Microsoft Corporation.
Networking OSI (Open Systems Interconnection) model of computer networking, seven layers (the Application, Presentation, Session, Transport, Network, Data.
RMI Example. Compilation: /home2/fccheng/temp/RMI2> javac MyObject.java /home2/fccheng/temp/RMI2> javac RemoteServer.java /home2/fccheng/temp/RMI2> javac.
UNIT - III WEB SERVICES BUILDING BLOCKS. Transport protocols for web services Transport such as HTTP and TCP are becoming common for SOAP traffic. However.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Advanced Tools for Multi- Threads Programming Avshalom Elmalech Eliahu Khalastchi 2010.
Concurrent TCP servers. The basic idea 1 client = 1 task. The task is alive as long until the connection is closed The task closes the connection.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 14 th Lecture Pavel Ježek
Lecture 6 Threads Erick Pranata
Computing with C# and the .NET Framework
Section 5.7 Concurrency, Interference, and Synchronization.
System Programming Practical Session 7
Socket programming with TCP
EE 422C Socket Programming
Windows Azure Storage Queue Storage.
CNT 4007C Project 2 Good morning, everyone. In this class, we will have a brief look at the project 2. Project 2 is basically the same with project 1.
網路程式設計 - C# 版 日期 : 2018/12/4.
Java Threads אליהו חלסצ'י תכנות מתקדם תרגול מספר 6
Multithreading 2 Lec 24.
Multi-routing the '.Net' Gigax, Kevin Edward Torres, Francisco Javier
Web Service.
.Net Sockets.
Visual Programming COMP-315
CPSC 441 UDP Socket Programming
Chapter 2: Application layer
Testing servers.
Multiplexing/Demux.
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Advanced .NET Programming I 15th Lecture
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Presentation transcript:

Параллельная работа сокетов в C#

Потоки в C# using System; using System.Threading; public class ThreadExample { public static void ThreadProc() { for (int i = 0; i < 10; i++) { Console.WriteLine("ThreadProc: {0}", i); Thread.Sleep(0); }

Потоки в C# public static void Main() { Console.WriteLine("Main thread: Start a second thread."); Thread t = new Thread(new ThreadStart(ThreadProc)); t.Start(); for (int i = 0; i < 4; i++) { Console.WriteLine("Main thread: Do some work."); Thread.Sleep(0); } Console.WriteLine("Main thread: Call Join()"); t.Join(); Console.WriteLine("Main thread: ThreadProc.Join has returned"); Console.ReadLine(); }

Потоки в C#  Объявление и создание потока, указывается метод-цель Thread t = new Thread(new ThreadStart(ThreadProc));  Запуск потока t.Start();  Приостановка потоков t.Suspend();  Возобновление приостановленного потока t.Resume();

Потоки в C#  Ожидание завершения потока t.Join();  Состояние ожидания и передача управления Thread.Sleep(0);

1 шаг изменения программы-сервера  Создадим метод run(), в задачи которого входит создание потока, чтение данных, их преобразование и запись в поток.  Фактически, здесь сосредоточена вся работа с клиентом.  Подключим: using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading;

Глобально объявим: public static TcpClient client; public static TcpListener server; private static System.Threading.Thread t;

Метод run() public static void run(TcpClient client) { Byte[] bytes = new Byte[256]; NetworkStream stream = client.GetStream(); int i; i = stream.Read(bytes, 0, bytes.Length); String data = System.Text.Encoding.UTF8.GetString(bytes, 0, i); Console.WriteLine(String.Format("Received: {0}", data)); data = data.ToUpper(); byte[] msg = System.Text.Encoding.UTF8.GetBytes(data); stream.Write(msg, 0, msg.Length); Console.WriteLine(String.Format("Sent: {0}", data)); client.Close(); Console.WriteLine("Close"); }

2 шаг используем метод run в цикле ожидания подключения клиента while(true) { Console.Write("Waiting for a connection... "); client = server.AcceptTcpClient(); Console.WriteLine("Connected!"); run(client); } Пока клиенты работают с сервером последовательно.

3 шаг -используем потоки для обеспечения параллельной работы сокетов  Добавим: using System.Threading;  Глобально объявим: private System.Threading.Thread t;  Создадим метод public static void ThreadProc() { run(client); }

4 шаг - создадим поток в цикле ожидания подключения клиента while(true) { Console.Write("Waiting for a connection... "); client = server.AcceptTcpClient(); Console.WriteLine("Connected!"); t=new Thread(new ThreadStart(ThreadProc)); t.Start(); }

5 шаг запуск сервера оформим в виде метода serverwork() public static void serverwork() { try { Int32 port=13000; IPAddress localAddr=IPAddress.Parse(" "); server=new TcpListener(localAddr,port); server.Start(); Byte[] bytes = new Byte[256]; while(true) {

Console.Write("Waiting for a connection... "); client = server.AcceptTcpClient(); Console.WriteLine("Connected!"); //run(client); t=new Thread(new ThreadStart(ThreadProc)); t.Start(); } catch(SocketException ex) { Console.WriteLine("SocketException: {0}", ex); }

6 шаг создадим метод, который запускает сервер public static void ThreadProc1() { serverwork(); }

7 шаг – кнопка «Запуск сервера» private void button3_Click(object sender, System.EventArgs e) { t=new Thread(new ThreadStart(ThreadProc1)); t.Start(); }

8 шаг – кнопка «Останов сервера» private void button2_Click(object sender, System.EventArgs e) { if (server!=null) { server.Stop(); t.Abort(); }

9 шаг – событие «Закрытие формы» private void Form1_Closed(object sender, System.EventArgs e) { if (server!=null) { server.Stop(); t.Abort(); }