Сообщение было отмечено Lord Demos как решение
Решение
клиент
| 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
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Net.Sockets;
using System.Data.OleDb;
namespace Client
{
public partial class Form1 : Form
{
private NetworkStream output;
private BinaryReader reader;
private BinaryWriter writer;
// сообщение от сервера
private string message = "";
private Thread readThread;
// сообщение серверу
private string stringSend;
// строка для добавления данных в таблицу
string stringToBase;
// температура выпечки текстолита
private double temperature;
// количество полученных досок
private int number;
// остаток массы
private double rests;
// строка, используемая для разбиения сообщения от сервера и записи данных в таблицу
private string[] stroka;
public Form1()
{
InitializeComponent();
//readThread = new Thread(new ThreadStart(RunClient));
//readThread.Start();
}
public void RunClient()
{
TcpClient client;
try
{
toolStripStatusLabel1.Text = "Ожидание подключения...";
client = new TcpClient();
client.Connect("localhost", 5000);
output = client.GetStream();
writer = new BinaryWriter(output);
reader = new BinaryReader(output);
toolStripStatusLabel1.Text = "Сервер подключен...";
writer.Write(stringSend);
try
{
message = reader.ReadString();
label6.Text = message;
button3.Enabled = true;
OleDbConnection conClient = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + @"clientPrice.mdb");
conClient.Open();
OleDbCommand deleteCommand = new OleDbCommand("DELETE * FROM clientTable", conClient);
deleteCommand.ExecuteNonQuery();
stroka = message.Split(' ');
temperature = Convert.ToDouble(stroka[2]);
number = Convert.ToInt32(stroka[9]);
rests = Convert.ToDouble(stroka[12]);
OleDbCommand insertCommand = new OleDbCommand("INSERT INTO clientTable VALUES (" + "'" + stringToBase + "','" + temperature + "','" + number + "','" + rests + "'" + ")", conClient);
insertCommand.ExecuteNonQuery();
conClient.Close();
}
catch (Exception)
{
System.Environment.Exit(System.Environment.ExitCode);
}
writer.Close();
reader.Close();
output.Close();
client.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
System.Environment.Exit(System.Environment.ExitCode);
}
private void button1_Click(object sender, EventArgs e)
{
label5.Visible = true;
if(radioButton1.Checked == true)
{
try
{
label5.Text = "Марка продукции: " + comboBox1.SelectedItem.ToString() + "-1-" + numericUpDown1.Value.ToString() + "-" + numericUpDown2.Value.ToString() + ".\nВес продукции: " + numericUpDown3.Value.ToString() + " кг";
stringSend = comboBox1.SelectedItem.ToString() + "-1-" + numericUpDown1.Value.ToString() + "-" + numericUpDown2.Value.ToString() + ".\nВес продукции: " + numericUpDown3.Value.ToString() + " кг.";
stringToBase = comboBox1.SelectedItem.ToString() + "-1-" + numericUpDown1.Value.ToString() + "-" + numericUpDown2.Value.ToString() + ". " + numericUpDown3.Value.ToString() + " кг.";
button2.Enabled = true;
}
catch
{
label5.Text = "Вы не заполнили все поля!";
}
}
if (radioButton2.Checked == true)
{
try
{
label5.Text = "Марка продукции: " + comboBox1.SelectedItem.ToString() + "-2-" + numericUpDown1.Value.ToString() + "-" + numericUpDown2.Value.ToString() + ".\nВес продукции: " + numericUpDown3.Value.ToString() + " кг";
stringSend = comboBox1.SelectedItem.ToString() + "-2-" + numericUpDown1.Value.ToString() + "-" + numericUpDown2.Value.ToString() + ".\nВес продукции: " + numericUpDown3.Value.ToString() + " кг.";
stringToBase = comboBox1.SelectedItem.ToString() + "-1-" + numericUpDown1.Value.ToString() + "-" + numericUpDown2.Value.ToString() + ". " + numericUpDown3.Value.ToString() + " кг.";
button2.Enabled = true;
}
catch
{
label5.Text = "Вы не заполнили все поля!";
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
/*
label1.BackColor = System.Drawing.Color.Transparent;
label2.BackColor = System.Drawing.Color.Transparent;
label3.BackColor = System.Drawing.Color.Transparent;
label4.BackColor = System.Drawing.Color.Transparent;
label5.BackColor = System.Drawing.Color.Transparent;
label6.BackColor = System.Drawing.Color.Transparent;
radioButton1.BackColor = System.Drawing.Color.Transparent;
radioButton2.BackColor = System.Drawing.Color.Transparent;
*/
radioButton1.Checked = true;
button2.Enabled = false;
button3.Enabled = false;
label5.Visible = false;
label6.Visible = true;
TcpClient client;
try
{
client = new TcpClient();
client.Connect("localhost", 5000);
toolStripStatusLabel1.Text = "Сервер подключен...";
}
catch
{
toolStripStatusLabel1.Text = "Ожидание подключения...";
}
}
private void button2_Click(object sender, EventArgs e)
{
label6.Visible = true;
try
{
RunClient();
}
catch { }
}
private void numericUpDown1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
private void numericUpDown2_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
private void numericUpDown3_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar))
e.Handled = true;
}
private void button3_Click(object sender, EventArgs e)
{
crystalForm crystalForm = new crystalForm();
crystalForm.ShowDialog();
}
}
} |
|
сервер
| 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
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
using System.Data.OleDb;
namespace Server
{
public partial class Form1 : Form
{
public OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + @"serverInfo.mdb");
public DataTable tempTable;
public OleDbDataAdapter dataAdapter;
private Socket connection;
// readThread принимает от клиентов запросы на соединение
private Thread readThread;
private BinaryWriter writer;
private BinaryReader reader;
private NetworkStream socketStream;
IPEndPoint clientEndPoint;
public string ipAddress = "";
public Form1()
{
InitializeComponent();
readThread = new Thread(new ThreadStart(RunServer));
readThread.Start();
}
// RunServer инициализирует сервер для получения запросов на соединение и их обработки
public void RunServer()
{
// создание listener для прослушивания клиентского запроса на соединение
TcpListener listener;
int counter = 1;
try
{
listener = new TcpListener(5000);
// начало ожидания запросов
listener.Start();
while (true)
{
toolStripStatusLabel1.Text = "Ожидание подключения...";
// вызов метода AcceptSocket, возвращающего при удачном соединении сокет
connection = listener.AcceptSocket();
socketStream = new NetworkStream(connection);
// создание экземпляров BinaryWriter и BinaryReader для считывания и записи данных
writer = new BinaryWriter(socketStream);
reader = new BinaryReader(socketStream);
toolStripStatusLabel1.Text = "Соединение установлено...";
// в переменной theReply будет храниться считываемая от клиента строка
string theReply = "";
do
{
try
{
// определение ip-адреса клиента, для вывода его на экран и последующей записи в базу данных
clientEndPoint = (IPEndPoint)connection.RemoteEndPoint;
// записываем ip-адрес в переменную ipAddress
ipAddress = clientEndPoint.Address.ToString();
theReply = reader.ReadString();
richTextBox2.Text += DateTime.Now.ToLongTimeString() + " запрос от клиента. IP-адрес: " + ipAddress + "\nМарка продукции: " + theReply + "\n\n";
writer.Write(countTemperature(theReply));
}
catch (Exception)
{
break;
}
}
while (connection.Connected);
writer.Close();
reader.Close();
socketStream.Close();
connection.Close();
++counter;
}
}
catch(Exception error)
{
MessageBox.Show(error.ToString());
}
}
// добавление новой записи в таблицу generalTable
public void addNewRecord(string ip, string type, string mass)
{
con.Open();
string nextAfterMaxId = "";
try
{
OleDbCommand maxId = new OleDbCommand("SELECT MAX([№ запроса]) FROM generalTable", con);
OleDbDataReader readId = maxId.ExecuteReader();
while (readId.Read())
nextAfterMaxId = Convert.ToString(int.Parse(readId[0].ToString()) + 1);
}
catch
{
nextAfterMaxId = "1";
}
OleDbCommand insertCommand = new OleDbCommand("INSERT INTO generalTable VALUES (" + "'" + nextAfterMaxId + "','" + ipAddress + "','" + DateTime.Now.ToString() + "','" + type + "','" + mass + "'" + ")", con);
if(insertCommand.ExecuteNonQuery()==1)
MessageBox.Show("Все прошло успешно.","Добавление",MessageBoxButtons.OK,MessageBoxIcon.Asterisk);
con.Close();
}
public string countTemperature(string reply)
{
// разделение строки, полученной от клиента, на подстроки
string[] parts = reply.Split('.');
// полная формула текстолита
string[] type = parts[0].Split('-');
// выделение из строки массы текстолита
string[] massa = parts[1].Split(' ');
// требуемая масса
int mass = Convert.ToInt32(massa[2]);
// марка текстолита
string mark = type[0];
// количество слоев фольги
int layer = Convert.ToInt32(type[1]);
// толщина фольги
int thickFoil = Convert.ToInt32(type[2]);
// толщина доски
double thickBoard = Convert.ToDouble(type[3]);
// количество досок, счетчик количества пакетов, остаточная масса
int thickNum, count = 0, ostatok = 0;//
// температура выпечки
double temperature;
addNewRecord(ipAddress, parts[0], massa[2]);
if (mark == "СТФ")
{
if (thickBoard < 2.0)
thickNum = 11;
else
if (thickBoard >= 2.0 && thickBoard < 3)
thickNum = 9;
else
thickNum = 7;
double tempMass = Convert.ToDouble(mass);
for (; ; )
{
if (tempMass >= (thickNum * 0.35))
{
tempMass = tempMass - thickNum * 0.35;
count++;
}
else
break;
}
temperature = thickNum * thickBoard * 10 + 10;
return "Температура выпечки: " + temperature.ToString() + " град.\nМасса 1й доски: 350" + " гр.\nКоличество досок: " + count.ToString() + " \nОстаток массы: " + Convert.ToString(Math.Round(tempMass, 2)) + " кг.";
}
else
{
if (thickBoard <= 1.5)
thickNum = 8;
else
if (thickBoard == 2.0)
thickNum = 7;
else
thickNum = 6;
double tempMass = Convert.ToDouble(mass);
for (; ; )
{
if (tempMass >= (thickNum * 0.35))
{
tempMass = tempMass - thickNum * 0.35;
count++;
}
else
break;
}
temperature = thickNum * thickBoard * 10 + 10;
return "Температура выпечки: " + temperature.ToString() + " град.\nМасса 1й доски: 350 гр." + "\nКоличество досок: " + count.ToString() + " \nОстаток массы: " + Convert.ToString(Math.Round(tempMass, 2)) + " кг.";
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
System.Environment.Exit(System.Environment.ExitCode);
}
private void открытьБазуДанныхToolStripMenuItem_Click(object sender, EventArgs e)
{
dataBase dataBase = new dataBase();
dataBase.ShowDialog();
}
private void Form1_Load(object sender, EventArgs e)
{
menuStrip1.BackColor = System.Drawing.Color.AliceBlue;
}
}
} |
|
я подумал, раз при пошаговом работает, может надо установить время ожидания клиента ответа от сервера?
Добавлено через 22 часа 34 минуты
продвинул проблему дальше - проверил в универе на машине - все работает, у друга на машине - все работает, не работает только у меня...кто может посоветовать, что делать? я уже винду несколько раз переставлял...и хр и 7, я просто не знаю что делать, если кто может, помогите пожалуйста
0
|