Форум программистов, компьютерный форум, киберфорум
C#: Веб-сервисы и WCF
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.60/5: Рейтинг темы: голосов - 5, средняя оценка - 4.60
0 / 0 / 0
Регистрация: 05.03.2013
Сообщений: 9
1

Падает сервер, после некоторых операций в клиент-серверном приложении

31.10.2016, 12:02. Показов 851. Ответов 2
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Добрый день! Есть Клиент -серверное приложение, сервер и клиент написан в отдельном файле. После отправки сообщений через сервер, в некоторых случаях он падает. При дебаге нашел ошибку: пишет что нельзя записывать в файл, так как он используется другим процессом(все это происходит при записи в лог файл.) Кто сможет правильно объяснить как нужно сделать открытие файла на запись и закрытие, чтобы он не падал каждый раз? Местоположение ошибки указал

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.IO;
namespace VoiceServer2_0
{
    class Server
    {
        private TcpListener tcpListener;
        private Thread listenThread;
 
        public Server(int PortNumber = 5000)
        {
            this.tcpListener = new TcpListener(IPAddress.Any, PortNumber);
            this.listenThread = new Thread(new ThreadStart(ListenForClients));
            this.listenThread.Start();
        }
 
    
 
        private void ListenForClients()
        {
            this.tcpListener.Start();
 
            while (true)
            {
                //blocks until a client has connected to the server
                TcpClient client = this.tcpListener.AcceptTcpClient();
 
                //create a thread to handle communication 
                //with connected client
                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(client);
            }
        }
 
 
        private void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();
 
            byte[] message = new byte[6];
            int bytesRead;
 
            while (true)
            {
               
                
                
                bytesRead = 0;
 
                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message,0,6);
                }
                catch
                {
                    //a socket error has occured
                    break;
                }
 
                if (bytesRead != 6)
                {
                    //the client has disconnected from the server
                    break;
                }
 
                var log = new StreamWriter("log.txt"); //ошибка вот с этим файлом
 
 
 
                //Retrive header from client
                string header = System.Text.Encoding.Default.GetString(message);
                int Senderid = (int)message[0];
                string cmd = header.Substring(1, 4);
                int ReceiverId = (int)message[5];
                bytesRead = 0;
 
                Console.WriteLine("{0} Command {1} received from {2} ",DateTime.Now, cmd, Senderid);
                Console.WriteLine("");
                log.WriteLine ("{0} Command {1} received from {2} ", DateTime.Now, cmd, Senderid);
                log.Close(); //+//
                switch (cmd)
                {
 
                //Receive file from SenderID and save it in /<SenderId>/<Filename>
                    case "SEND":
                        
                        byte[] myReadBuffer = new byte[1024];
                        Random RandomMessageId = new Random();
                        //DateTime DateMessage = new DateTime();
                        string s = DateTime.Now.ToString("dd-MM-yy_HH-mm-ss");
                        //string FileName ="From"+ Convert.ToString(Senderid)+ "_" +  Convert.ToString(RandomMessageId.Next(1,1000000)) + ".wav";
                        string FileName ="From"+ Convert.ToString(Senderid)+ "_" +  s + ".wav";
                        //Create Inbox Directory for Receiver if needed
                        if(Directory.Exists(Convert.ToString(ReceiverId)) == false)
                            Directory.CreateDirectory(Convert.ToString(ReceiverId));
 
                        string SavePath = Convert.ToString(ReceiverId) + "//" + FileName;
 
                    //Read data from Cliet by 1024 block and write to file. If file exist - append to this file. Otherwise create it
                        for (; ; )
                        {
                            bytesRead = clientStream.Read(myReadBuffer, 0, myReadBuffer.Length);
 
                            if (bytesRead == 0)
                                break;
 
                            if (File.Exists(SavePath) == false)
                            {
                                using (var stream = new FileStream(SavePath, FileMode.OpenOrCreate))
                                {
                                    stream.Write(myReadBuffer, 0, myReadBuffer.Length);
                                    stream.Close();
                                }
 
                            }
 
                            else
                            {
                                using (var stream = new FileStream(SavePath, FileMode.Append))
                                {
                                    stream.Write(myReadBuffer, 0, myReadBuffer.Length);
                                    stream.Close();
                                }
                            }
                        }
                         // Print out the received message to the console.
                        Console.WriteLine("Saved as " + FileName);
                        Console.WriteLine("");
                       
                        log.WriteLine("Saved as " + FileName);
                        log.Close(); //+//
                        
                        break;
 
 
                    //Send the list of inbox messages
                    case "LIST":
 
                        string SearchPath = Convert.ToString(Senderid) + "//";
                        if (Directory.Exists(Convert.ToString(Senderid)) == false)
                            Directory.CreateDirectory(Convert.ToString(Senderid));
                      
                        
                        //Check if directory is not empty
                        if (Directory.GetFiles(SearchPath).Length != 0)
                        {
                            string[] Files = Directory.GetFiles(SearchPath);
                            StringBuilder FileList = new StringBuilder();
                            foreach (string file in Files)
                            {
                                FileList.AppendLine(file);
                                //FileList.AppendLine(file.Substring(file.LastIndexOf("From")));
                            }
 
                            string tmp = Convert.ToString(FileList);
                            byte[] SendAsBytes = Encoding.ASCII.GetBytes(tmp);
                            clientStream.Write(SendAsBytes, 0, SendAsBytes.Length);
                            
                        }
 
                        else 
                        {
                            //If directory is null - send message 255 (Inbox is empty)
                            clientStream.WriteByte(255);
                        }
 
                      break;
 
                    case "GETM" :
 
                        
                      byte[] RequestedFile = new byte  [1024];
                      int NumberOfBytesRead;
                      NumberOfBytesRead =  clientStream.Read(RequestedFile,0,RequestedFile.Length);
                     string ReqFile = Encoding.ASCII.GetString(RequestedFile,0,NumberOfBytesRead);
                      
                      string SenderID = Convert.ToString(Senderid);
                      byte[] buff = File.ReadAllBytes(SenderID + "//" + ReqFile);
                      clientStream.Write(buff, 0, buff.Length);
                     // File.WriteAllBytes("log.wav", buff);
                      Console.WriteLine("File " + ReqFile + " sent to " + SenderID);
                        
                        log.WriteLine("File " + ReqFile + " sent to " + SenderID);
                       
                      break;
                       //Новый метод удаления
                    case "DEL":
                        byte[] RequestedFile1 = new byte  [2024];
                        int NumberOfBytesReadDel;
                        NumberOfBytesReadDel = clientStream.Read(RequestedFile1, 0, RequestedFile1.Length);
                        string ReqFile1 = Encoding.ASCII.GetString(RequestedFile1,0,NumberOfBytesReadDel);
                        string SenderID1 = Convert.ToString(Senderid);
                        File.Delete(SenderID1 + "//" + ReqFile1);
                        string SearchPath1 = Convert.ToString(Senderid) + "//";
 
                      
                        
                        //Check if directory is not empty
                        if (Directory.GetFiles(SearchPath1).Length != 0)
                        {
                            string[] Files = Directory.GetFiles(SearchPath1);
                            StringBuilder FileList = new StringBuilder();
                            foreach (string file in Files)
                            {
                                FileList.AppendLine(file);
                               // FileList.AppendLine(file.Substring(file.LastIndexOf("From")));
                            }
 
                            string tmp = Convert.ToString(FileList);
                            byte[] SendAsBytes = Encoding.ASCII.GetBytes(tmp);
                            clientStream.Write(SendAsBytes, 0, SendAsBytes.Length);
                            
                        }
 
                        else 
                        {
                            //If directory is null - send message 255 (Inbox is empty)
                            clientStream.WriteByte(255);
                        }
 
                      break;
                         
                }
                //log.Close();
                
 
 
 
                
               
            }
 
            tcpClient.Close();
            
        }
    }
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
31.10.2016, 12:02
Ответы с готовыми решениями:

Работа асинхронных операций в клиент-серверном приложении
Добрый день, не очень понимаю, как работает асинхронная операция? Есть сервер, к которому...

Аутентификация в клиент-серверном приложении
Доброго времени суток, граждане. Делаю клиент-серверное приложение с толстым клиентом....

Передача данных в клиент-серверном приложении
Добрый день. Я новичок в C# и возможно мой вопрос будет глупым, но сильно не ругайте, а...

Обработка ошибки в Клиент - Серверном приложении
Доброго времени суток. Писал чат на сокетах. Есть приложение Сервер и приложение Клиент. Клиент...

2
Эксперт .NET
5534 / 4298 / 1217
Регистрация: 12.10.2013
Сообщений: 12,332
Записей в блоге: 2
31.10.2016, 12:18 2
Цитата Сообщение от koresch Посмотреть сообщение
как нужно сделать открытие файла на запись и закрытие
Самое очевидное - использовать Dispose() для всего, что его реализует (особенно это касается потоков).
Создавайте все потоки через конструкцию usnig(), тогда по выходу из нее поток будет закрыт и вы сможете снова открыть файл.
Обратите внимание на строку 43, переменная clientStream. Вы его создаете, но его закрытия я не нашел.
1
0 / 0 / 0
Регистрация: 05.03.2013
Сообщений: 9
31.10.2016, 12:37  [ТС] 3
Спасибо, пока что помогло, будем дальше тестить
0
31.10.2016, 12:37
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
31.10.2016, 12:37
Помогаю со студенческими работами здесь

Организация авторизации в клиент-серверном приложении
Доброе утро. Пишу приложение - есть tcp-сервер и tcp-клиент. Нужно реализовать авторизацию...

Обработка изображения в клиент-серверном приложении
Приветствую! Ребят, подскажите, почему в клиент-серверном приложении не удается отобразить картинку...

Использование потоков в клиент-серверном приложении
Imports System.Net Imports System.Net.Sockets Imports System.IO Imports System.Threading Public...

Шифрование данных в клиент-серверном приложении
Всем привет :) Возникла острая необходимость шифрования текста. В чем соль. Результат шифровки...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru