public Write ( byte buffer, int offset, int size ) : void | ||
buffer | byte | |
offset | int | |
size | int | |
return | void |
public void Write(ref NetworkStream stream) { // write OpenCount stream.Write(BitConverter.GetBytes(this.OpenCount), 0, 4); // write SignList stream.WriteByte((byte)this.SignList.Count); foreach(ushort n in this.SignList) { stream.Write(BitConverter.GetBytes(n), 0, 2); } }
public static void SendString(NetworkStream client, string s) { var bytes = Encoding.UTF8.GetBytes(s); client.Write(BitConverter.GetBytes(bytes.Length), 0, 4); client.Write(bytes, 0, bytes.Length); client.Flush(); }
public override void Write(NetworkStream ns) { var s = File.ReadAllText(Content); var ws = new WebSharpInterpiter(s, Headers, req ); var cont = ws.Gencontent(); { var hds = Headers.ToString(); if (hds != "") { var buf = Encoding.ASCII.GetBytes(hds + Environment.NewLine); ns.Write(buf, 0, buf.Length); } } { var hds = ws.Headers.ToString(); if (hds != "") { var buf = Encoding.ASCII.GetBytes(hds + Environment.NewLine + Environment.NewLine); ns.Write(buf, 0, buf.Length); } } { var buf = Encoding.ASCII.GetBytes(cont); ns.Write(buf, 0, buf.Length); } }
//생성자 인자로 ServerIP와 보낼 파일의 FilePath를 받는다. public TCPSender(string ipAddress, int port, string FilePath, string FileName, int apikey) { try { tcpClient = new TcpClient(ipAddress, port); //TcpClient 객체 생성 및 ip와 연결 netStream = tcpClient.GetStream(); //데이터를 보내고 받는 NetworkStream 반환 fileStream = File.OpenRead(FilePath); //서버로 보낼 파일을 FileStream으로 부른다. // 파일 크기 전송 fileLength = fileStream.Length; //파일의 크기를 저장한다. byte[] buffer = BitConverter.GetBytes(fileLength); netStream.Write(buffer, 0, buffer.Length); // 파일 이름, 이름 크기 전송 byte[] filenamebuffer = System.Text.Encoding.UTF8.GetBytes(FileName); buffer = BitConverter.GetBytes(filenamebuffer.Length); netStream.Write(buffer, 0, buffer.Length); netStream.Write(filenamebuffer, 0, filenamebuffer.Length); // APIkey buffer = BitConverter.GetBytes(apikey); netStream.Write(buffer, 0, buffer.Length); FileSend(); //send = new Thread(new ThreadStart(FileSend)); //send 쓰레드 생성 //send.Start(); //쓰레드 시작으로 상태 전환 } catch(Exception e) { } }
public void Write(ref NetworkStream stream) { // write Index stream.Write(BitConverter.GetBytes(this.Index), 0, 4); // write Name stream.WriteByte((byte)this.Name.Length); byte[] _name = Encoding.ASCII.GetBytes(this.Name); stream.Write(_name, 0, _name.Length); }
public override void Write(NetworkStream ns) { { var buf = Encoding.ASCII.GetBytes(Headers.ToString() + Environment.NewLine + Environment.NewLine); ns.Write(buf, 0, buf.Length); } { var buf = Encoding.ASCII.GetBytes(Content); ns.Write(buf, 0, buf.Length); } }
/// <summary> /// 添加权限 /// </summary> /// <param name="dataStream"></param> /// <param name="in_message"></param> /// <param name="newClientInfo"></param> /// <returns></returns> public static Boolean AddPermission(NetworkStream dataStream, Message in_message, ClientInfo newClientInfo) { Message out_message = new Message(); //登陆确认命令 out_message.Command = Message.CommandHeader.AddPermission; //从输入信息中获取用户名、密码 string name = Encoding.Unicode.GetString(in_message.MessageBody).Split(':')[0]; string projectid = Encoding.Unicode.GetString(in_message.MessageBody).Split(':')[1]; int permissionlevel = Convert.ToInt32(Encoding.Unicode.GetString(in_message.MessageBody).Split(':')[2]); //用户名密码校验 Boolean isUserExisted = UserBussinessManager.UserExisted(name); if (!isUserExisted)//消息体需要根据数据库检索结果//同时初始化permission {//用户不存在 Console.WriteLine("添加权限:User doesn't existed!"); out_message.MessageBody = Encoding.Unicode.GetBytes(Constants.M_NOTEXISTED); //打包输出信息,将输出信息写入输出流 dataStream.Write(out_message.ToBytes(), 0, out_message.MessageLength); return false; } else { Boolean isPermissionExisted = PermissionExisted(name, projectid, permissionlevel); if (isPermissionExisted) {//权限已经存在 out_message.MessageBody = Encoding.Unicode.GetBytes(Constants.M_EXISTED); Console.WriteLine("添加权限:权限已经存在!"); //打包输出信息,将输出信息写入输出流 dataStream.Write(out_message.ToBytes(), 0, out_message.MessageLength); return false; } else { Console.WriteLine("添加权限:准备添加权限"); if (Database.insertPermission(name, projectid, permissionlevel)) { out_message.MessageBody = Encoding.Unicode.GetBytes(Constants.M_SUCCEED); Console.WriteLine("添加权限:" + name + " " + projectid + " " + permissionlevel.ToString() + "权限添加成功!"); //打包输出信息,将输出信息写入输出流 dataStream.Write(out_message.ToBytes(), 0, out_message.MessageLength); return true; } return false; } } }
private SmtpResponse SendCommand(NetworkStream networkStream, StreamReader streamReader, string command, params SmtpStatusCode[] goodReplys) { var dataBuffer = Encoding.ASCII.GetBytes(command + "\r\n"); networkStream.Write(dataBuffer, 0, dataBuffer.Length); return this.AcceptResponse(streamReader, goodReplys); }
private void send(NetworkStream networkStream, Byte[] bufferOut) { //------------------------------------------------Send message networkStream.Write(bufferOut, 0, bufferOut.Length); networkStream.Flush(); base.ByteSent += bufferOut.Length; }
public override void Flush(NetworkStream ns) { MinecraftStream Write = new MinecraftStream(); Write.WriteLong(Payload); var buf = Write.Flush(ID); ns.Write(buf, 0, buf.Length); }
private void ServerConnection(NetworkStream stream) { int RecievedSymbols = 0; byte[] recieved = new byte[2048]; byte[] to_send = new byte[2048]; string task = ""; while ( (RecievedSymbols = stream.Read(recieved, 0, recieved.Length)) > 0 ) { task = Resize(recieved); task = TaskToDo(task); Console.WriteLine(task); if (task.Equals("closed -1")) { to_send = Encoding.ASCII.GetBytes(task); stream.Write(to_send, 0, to_send.Length); client.Close(); return; } else { to_send = Encoding.ASCII.GetBytes(task); stream.Write(to_send, 0, to_send.Length); } Array.Clear(to_send, 0, to_send.Length); Array.Clear(recieved, 0, recieved.Length); } }
private void button2_Click(object sender, EventArgs e) { readData = "Conected to Chat Server ..."; msg(); clientSocket.Connect("127.0.0.1", 8888); serverStream = clientSocket.GetStream(); byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox3.Text + "$"); serverStream.Write(outStream, 0, outStream.Length); serverStream.Flush(); Thread ctThread = new Thread(getMessage); ctThread.Start(); }
public override void Flush(NetworkStream ns) { MinecraftStream read = new MinecraftStream(); read.WriteString(Json); var buf = read.Flush(ID); ns.Write(buf, 0, buf.Length); }
/** * Function to send a message to the server * \param stream - The stream to write to * \param msg - The message to send * \return - Retun true on success, false on failure */ private bool sendMessage(NetworkStream stream, Message msg) { string json = JsonConvert.SerializeObject(msg); using (MemoryStream mstream = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(mstream)) { byte[] encodedJson = Encoding.UTF8.GetBytes(json); writer.Write(hostToBig_i32(encodedJson.Length)); writer.Write(encodedJson); } byte[] request = mstream.ToArray(); try { stream.Write(request, 0, request.Length); stream.Flush(); } catch(SocketException ex) { Message emsg = new Message("error_socket", null); emsg.AddParameter("error_code", ex.ErrorCode); emsg.AddParameter("message", ex.Message); recvq.Enqueue(emsg); return false; } } return true; }
public void Post(NetworkStream stream) { StreamWriter writer = new StreamWriter(stream); writer.WriteLine("{0} {1}\r\nServer: {2}\r\nContent-Type: {3}\r\nAccept-Ranges: bytes\r\nContent-Length: {4}\r\n", HttpServer.VERSION, status, HttpServer.Name, mime, data.Length); stream.Write(data, 0, data.Length); }
private void SendToPipe(byte[] data, byte[] tag) { byte[] newData = new byte[tag.Length + 2 + data.Length]; tag.CopyTo(newData, 0); byte[] dataLen = BitConverter.GetBytes((ushort)data.Length); dataLen.CopyTo(newData, tag.Length); data.CopyTo(newData, tag.Length + 2); if (null == m_tcpStream) { return; } lock (m_tcpStream) { try { m_tcpStream.Write(newData, 0, newData.Length); } catch (Exception) { OnPipeDead(EventArgs.Empty); } } }
public string SendAndRecv(string order) { System.Net.Sockets.NetworkStream ns = this.TCPSocket.GetStream(); ns.ReadTimeout = 5000; ns.WriteTimeout = 5000; byte[] str = MakePacket(order); ns.Write(str, 0, str.Length); byte[] resBytes = new byte[this.TCPSocket.ReceiveBufferSize]; int resSize = ns.Read(resBytes, 0, resBytes.Length); if (resSize <= 5) { if (resSize <= 0) { this.ErrorMessage = ""; return(""); } if (resBytes[0] == '-') { this.ErrorMessage = R._("メッセージを送信できません。エラーコードが戻りました。\r\n送信データ:\r\n{0}", str.ToString()); return(""); } this.ErrorMessage = R._("サーバがおかしな応答を返しました。\r\n送信データ:\r\n{0}\r\n受信データ:\r\n{1}", str.ToString(), U.subrange(resBytes, 0, (uint)resSize).ToString()); return(""); } // return Encoding.ASCII.GetString(resBytes, 0, resSize); return(UnPacket(resBytes, resSize)); }
static void Main(string[] args) { Console.Write("Please enter your name: "); userName = Console.ReadLine(); client = new TcpClient(); try { client.Connect(host, port); stream = client.GetStream(); string message = userName; byte[] data = Encoding.Unicode.GetBytes(message); stream.Write(data, 0, data.Length); Thread receiveThread = new Thread(new ThreadStart(ReceiveMessage)); receiveThread.Start(); Console.WriteLine("Wellcome, {0}", userName); SendMessage(); } catch(Exception ex) { Console.WriteLine(ex.Message); } finally { Disconnect(); } }
// Camera parameter を取得する static string GetCameraParameterInJson(string ipAddress) { TcpClient tcp = new TcpClient(ipAddress, SHOOTIMAGESERVER_PORT); System.Net.Sockets.NetworkStream ns = tcp.GetStream(); ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; // get parameter コマンドを送信 string cmd = "PGT"; byte[] cmdBytes = System.Text.Encoding.UTF8.GetBytes(cmd); ns.Write(cmdBytes, 0, cmdBytes.Length); // データを受信 while (tcp.Client.Available == 0) { } byte[] rcvBytes = new byte[tcp.Client.Available]; ns.Read(rcvBytes, 0, tcp.Client.Available); string rcvString = System.Text.Encoding.UTF8.GetString(rcvBytes); tcp.Close(); return(rcvString); }
public OutboundPacket(NetworkStream stream, String command) { command = "!1" + command; int dataSize = command.Length + _packetFooter.Length; int packetSize = _packetHeaderTotalSize + dataSize; byte[] message = new byte[packetSize]; int pos = 0; foreach (byte b in _packetHeader) message[pos++] = b; foreach (byte b in BitConverter.GetBytes(dataSize).Reverse()) message[pos++] = b; message[pos++] = _protocolVersion; pos += 3; foreach (byte b in System.Text.Encoding.ASCII.GetBytes(command)) message[pos++] = b; foreach (byte b in _packetFooter) message[pos++] = b; stream.Write(message, 0, message.Length); try { System.Threading.Thread.Sleep(100); } catch (Exception) { } }
private static void Main(string[] args) { Console.Write("Введите свое имя: "); _userName = Console.ReadLine(); _client = new TcpClient(); try { _client.Connect(Host, Port); _stream = _client.GetStream(); var message = _userName; if (message != null) { var data = Encoding.Unicode.GetBytes(message); _stream.Write(data, 0, data.Length); } var receiveThread = new Thread(ReceiveMessage); receiveThread.Start(); Console.WriteLine($"Добро пожаловать, {_userName}"); SendMessage(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Disconnect(); } }
public override void Respond(TcpClient client, NetworkStream stream, byte[] message) { string msgIncoming = Encoding.ASCII.GetString(message, 0, message.Length); System.Diagnostics.Debug.WriteLine("RECEIVED//" + msgIncoming + "//"); switch (msgIncoming) { case REQ_SEND_CLASS_LIST: List<Class> classList = _helper.GetClasses(); SendData(classList, stream); break; case REQ_SEND_STUD_LIST: System.Diagnostics.Debug.WriteLine("Requesting class ID"); string msgToSend = CMD_SEND_CLASS_ID; byte[] bytesToSend = Encoding.ASCII.GetBytes(msgToSend); stream.Write(bytesToSend, 0, bytesToSend.Length); message = new byte[5]; stream.Read(message, 0, message.Length); msgIncoming = Encoding.ASCII.GetString(message, 0, message.Length).Trim(); System.Diagnostics.Debug.WriteLine("RECEIVED//" + msgIncoming + "//"); List<Student> studentsList = _helper.GetStudentsInClass(new Class(Convert.ToInt32(msgIncoming), "")); SendData(studentsList, stream); break; } }
public void sendNotify(string notify) { try { client.Connect(serverName, port); stream = client.GetStream(); UnicodeEncoding encoder = new UnicodeEncoding(); byte[] buffer = encoder.GetBytes(notify); stream.Write(buffer, 0, buffer.Length); } catch (SocketException ex) { Trace.TraceError(String.Format("unClientClass says: {0}", ex.Message)); } finally { if (stream != null) { stream.Close(); } if (client.Connected) { client.Close(); } } }
/// <summary> /// 获取通信返回信息 /// </summary> /// <param name="cmd">命令</param> /// <param name="stream"></param> /// <returns></returns> public static void Work(string cmd, NetworkStream stream) { Byte[] buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(cmd); stream.Write(buffer, 0, buffer.Length); Console.WriteLine("发送信息:" +cmd); buffer = new Byte[1024]; StringBuilder sb = new StringBuilder(); Int32 numberOfBytesRead = 0; do { numberOfBytesRead = stream.Read(buffer, 0, buffer.Length); sb.Append(System.Text.Encoding.GetEncoding("GB2312").GetString(buffer, 0, numberOfBytesRead)); } while (stream.DataAvailable); string result = sb.ToString(); if (string.IsNullOrEmpty(result)) Console.WriteLine("DServer无响应,请检查服务是否正常运行."); if (result.StartsWith("OK")) { if (result.Length == 2) { Console.WriteLine("任务已接收"); } else { Console.WriteLine(result.Substring(3)); } } }
public static async Task SendTransportPacket(NetworkStream sw, TransportPacketType type, byte[] Data) { TransportPacket tp = new TransportPacket(Data, type, Constants.TransportVersion); byte[] msg = PacketCodec.CreateTransportPacket(tp); sw.Write(msg, 0, msg.Length); await sw.FlushAsync(); }
private void button2_Click(object sender, EventArgs e) { try { readData = "Connected to Chat Server ..."; msg(); clientSocket.Connect("127.0.0.1", 8888); serverStream = clientSocket.GetStream(); byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$"); serverStream.Write(outStream, 0, outStream.Length); serverStream.Flush(); Thread ctThread = new Thread(getMessage); ctThread.Start(); if(strUser == null) { strUser = textBox2.Text; Registry.SetValue(keyName, "user", strUser); } buttonSend.Enabled = true; } catch(Exception ex) { buttonSend.Enabled = false; } }
public override void Flush(NetworkStream ns) { MinecraftStream read = new MinecraftStream(); read.WriteVarInt(KeepAliveID); var buf = read.Flush(ID); ns.Write(buf, 0, buf.Length); }
public Client(Common.ServerConfig config, NameValueCollection appSettings, int myID, bool receiveOnly) : base(appSettings) { ClientRetryTime = Convert.ToInt32(appSettings["ClientRetryTime"]); tcpClient = AttemptTCPConnect(config); ns = tcpClient.GetStream(); //give them our id Console.WriteLine("Sending id: {0}", myID); byte[] buffer = BitConverter.GetBytes(myID); ns.Write(buffer, 0, 4); Console.WriteLine("Sent id"); TCPThreadState TCPState = new TCPThreadState(myID, ns); Thread receiveThread = new Thread(ReceiveThread); receiveThread.Start(TCPState); if (!receiveOnly) { Thread broadcastThread = new Thread(BroadcastThread); broadcastThread.Start(TCPState); } }
private void HandleRequest(object conSocket) { var connectionSocket = (Socket)conSocket; Stream ns = new NetworkStream(connectionSocket); var sr = new StreamReader(ns); var sw = new StreamWriter(ns); try { var line = "dummy"; var requestRaw = ""; while (line != "\r\n") { line = sr.ReadLine() + "\r\n"; requestRaw += line; } var request = new HttpRequest(requestRaw); var response = new HttpResponse(request.Uri); StopServer = request.MessageType == "EXIT"; var responseBytes = response.ToBytes(); ns.Write(responseBytes, 0, responseBytes.Length); } finally { sw.Close(); sr.Close(); ns.Close(); connectionSocket.Close(); } }
/// <summary> /// Send an SMTP command /// </summary> /// <param name="command"></param> /// <param name="expected"></param> /// <returns></returns> private bool SmtpCommand(string command, Response expected) { _stack.Push(command); byte[] buffer = Encoding.ASCII.GetBytes(_stack.Peek().ToString()); _stream.Write(buffer, 0, buffer.Length); return(this.ValidResponse(expected)); }
public override void Write(ref NetworkStream stream) { // write id & size stream.Write(BitConverter.GetBytes((ushort)this.ID), 0, 2); stream.Write(BitConverter.GetBytes(this.BodySize), 0, 4); // write loginserverip stream.WriteByte((byte)this.LoginServerIP.Length); stream.Write(Encoding.ASCII.GetBytes(this.LoginServerIP), 0, this.LoginServerIP.Length); // write loginserverport stream.Write(BitConverter.GetBytes(this.LoginServerPort), 0, 4); // write authkey stream.Write(BitConverter.GetBytes(this.AuthKey), 0, 4); }
public virtual void send(NetworkStream ns) { if (data == null) { getBytes (); } ns.Write (data, 0, data.Length); ns.Flush (); }
internal static void Write(NetworkStream stream, string data) { //prepend the length of the data to the message, and convert to bytes byte[] bytes = Encoding.ASCII.GetBytes(data.Length.ToString() + SIZE_PREFIX_DELIM + data); // send message stream.Write(bytes, 0, bytes.Length); }
/* This procedure puts a message on the current client stream. */ private void sendClient(String message) { byte[] bytesToSend = Encoding.UTF8.GetBytes(message); stream.Write(bytesToSend, 0, bytesToSend.Length); /* Since we're writing something, flush() must be used. */ stream.Flush(); Debug.Log("answer was sent: " + message); }
public void Write(NetworkStream stream) { stream.WriteByte((byte)this.Type); StreamHelper.WriteInt(stream, this.X); StreamHelper.WriteInt(stream, this.Z); StreamHelper.WriteShort(stream, Size); for (int i = 0; i < this.Size; i++) { StreamHelper.WriteShort(stream, CoordinateArray[i]); } stream.Write(this.TypeArray, 0, this.TypeArray.Length); stream.Write(this.MetadataArray, 0, this.MetadataArray.Length); stream.Flush(); }
private void button2_Click(object sender, EventArgs e) { try { string[] sendfiles = textBoxData.Text.ToString().Split(','); foreach (string filename in sendfiles) { FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); int fileSize = (int)fs.Length; // ファイルのサイズ byte[] buf = new byte[fileSize]; // データ格納用配列 int readSize; // Readメソッドで読み込んだバイト数 int remain = fileSize; // 読み込むべき残りのバイト数 int bufPos = 0; // データ格納用配列内の追加位置 while (remain > 0) { // 1024Bytesずつ読み込む readSize = fs.Read(buf, bufPos, Math.Min(1024, remain)); bufPos += readSize; remain -= readSize; } fs.Dispose(); if (comboBoxType.SelectedIndex == 0) { m_ns.Write(buf, 0, fileSize); } else if (comboBoxType.SelectedIndex == 1) { if (state != null) { if (state.workSocket != null) { TcpServerSend(state.workSocket, buf); } } } else if (comboBoxType.SelectedIndex == 2) { if (m_udp != null) { UdpSend(buf); } } } // listBox1.Items.Add("送信成功"); } catch (Exception) { // listBox1.Items.Add("送信失敗"); } }
public void sendToClient(string msg, TcpClient tcpClient) { try { System.Net.Sockets.NetworkStream ns = tcpClient.GetStream(); byte[] sendbuffer = System.Text.Encoding.ASCII.GetBytes(msg); ns.Write(sendbuffer, 0, sendbuffer.Length); //Debug.Write("To phone: " + msg + "\n"); } catch (Exception ex) { Debug.Write("Error in sendToSmartphone: " + ex); } }
public void SendMessage(byte[] bytesToSend) { try { //Send the text System.Net.Sockets.NetworkStream ns = default(System.Net.Sockets.NetworkStream); lock (Client.GetStream()) { ns = Client.GetStream(); //byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(msg); ns.Write(bytesToSend, 0, bytesToSend.Length); ns.Flush(); } } catch (Exception ex) { //MessageBox.Show(ex.ToString); } }
public void DisconnectFromServer() { print("Disconnect form Server"); if (ns != null) { byte[] ba = new byte[] { 0x65, 0x6e, 0x64 };//System.Text.Encoding.Unicode.GetBytes ("end"); ns.Write(ba, 0, ba.Length); ns.Flush(); //閉じる ns.Close(); tcp.Close(); } isConnectedToServer = false; }
public void Send(System.Net.Sockets.NetworkStream stream) { try { var bytes = Bytes(); if (length <= 1) { return; } stream.Write(bytes, 0, length); Server.statsPacketsSent++; Server.statsBytesSent += length; } catch (System.IO.IOException) { Godot.GD.Print("Sending disrupted"); } }
/// <summary> /// 发送数据 /// </summary> /// <param name="data"></param> public void sendData(Stream sr) { System.Net.Sockets.NetworkStream ns = tcpClient1.GetStream(); byte[] bs = new byte[128]; int num = 0; // sr.Position = 0; while (sr.CanRead) { num = sr.Read(bs, 0, bs.Length); ns.Write(bs, 0, num); } // sr.CopyTo(ns); ns.Flush(); }
/// <summary> /// Pipe functions. /// From read pipe to socket /// From socket to write pipe /// </summary> static void ReadPipeToSocket(System.Net.Sockets.NetworkStream networkStream, StreamString ss) { Task.Factory.StartNew(() => { String dataEncoded; byte[] dataDecoded; while (true) { dataEncoded = ss.ReadString(); dataDecoded = Convert.FromBase64String(dataEncoded); if (dataDecoded.Length > 0) { Console.WriteLine("ReadPipeToSocket: Encoded " + dataEncoded.Length + " / Decoded " + dataDecoded.Length); networkStream.Write(dataDecoded, 0, dataDecoded.Length); } } }); }
public void sendtcp(string sendMsg) { string ipOrHost = "127.0.0.1"; int port = 8080; System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(ipOrHost, port); Console.WriteLine("サーバー({0}:{1})と接続しました({2}:{3})。", ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port); System.Net.Sockets.NetworkStream ns = tcp.GetStream(); ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; System.Text.Encoding enc = System.Text.Encoding.UTF8; byte[] sendBytes = enc.GetBytes(sendMsg + '\n'); ns.Write(sendBytes, 0, sendBytes.Length); Console.WriteLine(sendMsg); System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; resSize = ns.Read(resBytes, 0, resBytes.Length); if (resSize == 0) { Console.WriteLine("サーバーが切断しました。"); } string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); //末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); Console.WriteLine(resMsg); //閉じる ns.Close(); tcp.Close(); }
//send data from list private void SendDataFromList() { try { while (true) { if (ClientNetMgr.GetSingle().IsConnect()) { if (m_SendDataList.Count <= 0) { Thread.Sleep(30); continue; } //Debug.Log("SendData:Send Count!"+m_SendDataList.Count); System.Net.Sockets.NetworkStream netStream = ClientNetMgr.GetSingle().GetNetworkStream(); lock (netStream) { if (netStream != null && netStream.CanWrite) { lock (m_SendDataList) { CSendData data = (CSendData)m_SendDataList[0]; netStream.Write(data.m_bDataList, 0, data.m_nLength); m_SendDataList.RemoveAt(0); //Debug.Log( "<color=#FFc900>Send packet:</color>"+ data.m_nMessageID); //Debug.Log("Send packet:" + data.m_nMessageID); } } } } else { //CloseSendThread(); break; } } } catch (System.Exception ex) { Debug.Log(ex.Message); } }
public void SendMessage(Chat.Packet msg) { try { //Send the text System.Net.Sockets.NetworkStream ns = default(System.Net.Sockets.NetworkStream); lock (_client.GetStream()) { ns = _client.GetStream(); // Serialize the message string message = ""; message = Chat.Serialize(msg); byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message); ns.Write(bytesToSend, 0, bytesToSend.Length); ns.Flush(); } } catch (Exception ex) { //MessageBox.Show(ex.ToString); } }
/// <summary> /// 发送数据 /// </summary> /// <param name="data"></param> public void sendData(byte[] data) { lock (this) { try { System.Net.Sockets.NetworkStream ns = tcpClient1.GetStream(); ns.Write(data, 0, data.Length); ns.Flush(); } catch (ObjectDisposedException ex2) { connectionDisconnection(); } catch (IOException ex3) { connectionDisconnection(); } } }
public bool SendMessage(byte[] bytesToSend) { Exception = null; bool result = false; try { //Send the text if (TCP.Connected == true) { System.Net.Sockets.NetworkStream ns = default(System.Net.Sockets.NetworkStream); lock (TCP.GetStream()) { ns = TCP.GetStream(); //byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(msg); //Sends the text ns.Write(bytesToSend, 0, bytesToSend.Length); ns.Flush(); } result = true; } else { //If the client is unable to connect to the IM server //and it tries to send a message, it will display this message. Exception = "Your connection to the server was lost."; } } catch (Exception ex) { Exception = ex.ToString(); } return(result); }
/* This function will get started by a new client-specific thread to handle its communication */ public void handleClient(object obj) { // retrieve client from parameter passed to thread TcpClient client = (TcpClient)obj; System.Net.Sockets.NetworkStream currentStream = client.GetStream(); /* If we have to send the same instruction to all clients, we order all client handlers to do so. */ while (true) { if (toAllClients) { byte[] bytesToSend = Encoding.UTF8.GetBytes(currentInstruction); currentInstruction = "N"; currentStream.Write(bytesToSend, 0, bytesToSend.Length); /* Since we're writing something, flush() must be used. */ currentStream.Flush(); Debug.Log("answer was sent: " + currentInstruction); } System.Threading.Thread.Sleep(1000); } }
/// <summary> /// send message to others /// </summary> /// <param name="destinationIP">the destination ip ,e.g.,192.168.1.1</param> /// <param name="msg">message you want to send</param> public static void SendMessage(string destinationIP, string msg) { System.Net.Sockets.TcpClient tcpClient = null; System.Net.Sockets.NetworkStream netStream = null; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg); var destIP = System.Net.IPAddress.Parse(destinationIP); var myIP = Communication.GetLocalIP(); //var myIP = "192.10.110.54"; var epDest = new System.Net.IPEndPoint(destIP, 1124); Random ro = new Random(); int up = 1150; int down = 1123; var sendport = 1123; while (!FunctionUtils.checkPort(sendport.ToString()))//检查端口占用 { sendport = ro.Next(down, up); } var dpLocal = new System.Net.IPEndPoint(myIP, sendport); tcpClient = new System.Net.Sockets.TcpClient(dpLocal); tcpClient.Connect(epDest); netStream = tcpClient.GetStream(); if (netStream.CanWrite) { netStream.Write(buffer, 0, buffer.Length); } tcpClient.GetStream().Close(); tcpClient.Client.Close(); tcpClient.Close(); // tcpClient.GetStream().Close(); // tcpClient.Client.Disconnect(false); //tcpClient.Close(); }
private void beginTradingToolStripMenuItem_Click(object sender, EventArgs e) { // Create three stocks and add them to the market Subject = new RealTimedata(); // In this lab assignment we will add three companies only using the following format: // Company symbol , Company name , Open price Subject.addCompany("MSFT", "Microsoft Corporation", 46.13); Subject.addCompany("AAPL", "Apple Inc.", 105.22); Subject.addCompany("FB", "Facebook, Inc.", 80.67); this.watchToolStripMenuItem.Visible = true; this.ordersToolStripMenuItem.Visible = true; this.beginTradingToolStripMenuItem.Enabled = false; this.marketToolStripMenuItem.Text = "&Join <<Connected>>"; clientSocket.Connect(txtServerIP.Text, Convert.ToInt32(txtServerPort.Text)); System.Net.Sockets.NetworkStream netStream = clientSocket.GetStream(); Byte[] sendRegister = Encoding.UTF8.GetBytes("REGISTER/" + txtUsername.Text + "/" + txtClientIP.Text + "/" + txtClientPort.Text); netStream.Write(sendRegister, 0, sendRegister.Length); MarketDepthSubMenu(this.marketByOrderToolStripMenuItem1); MarketDepthSubMenu(this.marketByPriceToolStripMenuItem1); }
/// <summary> /// 发送单个文件 /// </summary> /// <param name="client"></param> /// <param name="task"></param> /// <param name="item"></param> void PerformSendFile(TcpClient client, FileTaskInfo task, FileTaskItem item) { System.IO.FileStream fs = null; System.Net.Sockets.NetworkStream writer = null; try { writer = client.GetStream(); } catch (Exception) { TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure); return; } try { fs = new System.IO.FileStream(item.FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read); } catch (Exception) { if (writer != null) { writer.Close(); } TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure); OnFileSystemOperationError(new FileSystemOperationErrorEventArgs(FileSystemOperationType.OpenFileToSend, item.FullPath, task.RemoteHost)); return; } using (fs) { //检测断点数据是否正确 if (item.CurrentFileTransfered < 0 || item.CurrentFileTransfered > (ulong)fs.Length) { item.CurrentFileTransfered = 0; } fs.Seek((long)item.CurrentFileTransfered, System.IO.SeekOrigin.Begin); //设置当前任务信息 item.CurrentFileSize = (ulong)fs.Length; TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Processing); item.StartTime = DateTime.Now; using (writer) { byte[] buffer = new byte[SendBuffer]; //缓冲区 while (item.CurrentFileTransfered < item.CurrentFileSize) { int bytesRead = fs.Read(buffer, 0, buffer.Length); try { writer.Write(buffer, 0, bytesRead); } catch (Exception) { TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure); break; } //更新进度 item.CurrentFileTransfered += (ulong)bytesRead; item.FinishedSize += (ulong)bytesRead; } item.FinishedFileCount++; writer.Close(); } fs.Close(); //标记任务完成 if (item.State != FileTaskItemState.Failure) { TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Finished); } } }
public static void Main() { //サーバーに送信するデータを入力してもらう Console.WriteLine("文字列を入力し、Enterキーを押してください。"); string sendMsg = Console.ReadLine(); //何も入力されなかった時は終了 if (sendMsg == null || sendMsg.Length == 0) { return; } //サーバーのIPアドレス(または、ホスト名)とポート番号 string ipOrHost = "127.0.0.1"; //string ipOrHost = "localhost"; int port = 2001; //TcpClientを作成し、サーバーと接続する System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(ipOrHost, port); Console.WriteLine("サーバー({0}:{1})と接続しました({2}:{3})。", ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port); //NetworkStreamを取得する System.Net.Sockets.NetworkStream ns = tcp.GetStream(); //読み取り、書き込みのタイムアウトを10秒にする //デフォルトはInfiniteで、タイムアウトしない //(.NET Framework 2.0以上が必要) ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; //サーバーにデータを送信する //文字列をByte型配列に変換 System.Text.Encoding enc = System.Text.Encoding.UTF8; byte[] sendBytes = enc.GetBytes(sendMsg + '\n'); //データを送信する ns.Write(sendBytes, 0, sendBytes.Length); Console.WriteLine(sendMsg); //サーバーから送られたデータを受信する System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; do { //データの一部を受信する resSize = ns.Read(resBytes, 0, resBytes.Length); //Readが0を返した時はサーバーが切断したと判断 if (resSize == 0) { Console.WriteLine("サーバーが切断しました。"); break; } //受信したデータを蓄積する ms.Write(resBytes, 0, resSize); //まだ読み取れるデータがあるか、データの最後が\nでない時は、 // 受信を続ける } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); //受信したデータを文字列に変換 string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); //末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); Console.WriteLine(resMsg); //閉じる ns.Close(); tcp.Close(); Console.WriteLine("切断しました。"); Console.ReadLine(); }
static void Main(string[] args) { // Loading SyncshooterDefs var defs = SyncshooterDefs.Deserialize(@"..\..\syncshooterDefs.json"); // TEST defs.Serialize(@"..\..\syncshooterDefs_copy.json"); // UDP マルチキャストを開く MultiCastClient mcastClient = new MultiCastClient(MCAST_GRP, MCAST_PORT); if (mcastClient.Open() == false) { return; } //mcastClient.SendCommand( "SDW" ); // TEST // 接続しているラズパイのアドレスとポートを列挙する var mapIPvsPort = GetConectedHostAddress(mcastClient); // Camera parameter を取得する Console.Error.WriteLine("Get and save camera parameters..."); foreach (var pair in mapIPvsPort) { IPAddress adrs = pair.Key; string text = GetCameraParameterInJson(adrs.ToString()); Console.WriteLine("{0}", text); var param = JsonConvert.DeserializeObject <CameraParam>(text); string path = string.Format(@"..\..\cameraParam_{0}.json", adrs.ToString()); param.Serialize(path); } // Preview image の取得 Console.Error.WriteLine("Previewing..."); foreach (var pair in mapIPvsPort) { IPAddress adrs = pair.Key; TcpClient tcp = new TcpClient(adrs.ToString(), SHOOTIMAGESERVER_PORT); System.Net.Sockets.NetworkStream ns = tcp.GetStream(); ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; Console.WriteLine("IP Address: {0}", adrs); System.IO.MemoryStream ms = new System.IO.MemoryStream(); // get preview image コマンドを送信 string cmd = "PRV"; byte[] cmdBytes = System.Text.Encoding.UTF8.GetBytes(cmd); ns.Write(cmdBytes, 0, cmdBytes.Length); // データを受信 while (ns.DataAvailable == false) { } ulong sum = 0; ulong bytes_to_read = 0; do { byte[] rcvBytes = new byte[tcp.Client.Available]; int resSize = ns.Read(rcvBytes, 0, rcvBytes.Length); if (sum == 0) { // 先頭の4バイトには、次に続くデータのサイズが書かれている bytes_to_read = ((ulong)rcvBytes[0]) | ((ulong)rcvBytes[1] << 8) | ((ulong)rcvBytes[2] << 16) | ((ulong)rcvBytes[3] << 24); Console.WriteLine("bytes_to_read = {0}", bytes_to_read); } sum += (ulong)resSize; ms.Write(rcvBytes, 0, resSize); } while (sum < bytes_to_read + 4); Console.WriteLine("size = {0}", (int)sum - 4); ms.Close(); String path = string.Format("preview_{0}.bmp", adrs.ToString()); using (var fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite)) { fs.Write(ms.GetBuffer(), 4, (int)sum - 4); } ns.Close(); tcp.Close(); } // // Full image (JPG) の取得 // Multicast で 撮影コマンドを送信 mcastClient.SendCommand("SHJ"); Console.Error.WriteLine("Capturing JPEG..."); // Full image の取得 foreach (var pair in mapIPvsPort) { IPAddress adrs = pair.Key; TcpClient tcp = new TcpClient(adrs.ToString(), SHOOTIMAGESERVER_PORT); System.Net.Sockets.NetworkStream ns = tcp.GetStream(); ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; Console.WriteLine("IP Address: {0}", adrs); System.IO.MemoryStream ms = new System.IO.MemoryStream(); // full image 取得コマンドを送信 string cmd = "IMG"; byte[] cmdBytes = System.Text.Encoding.UTF8.GetBytes(cmd); ns.Write(cmdBytes, 0, cmdBytes.Length); // データを受信 while (ns.DataAvailable == false) { } ulong sum = 0; ulong bytes_to_read = 0; do { byte[] rcvBytes = new byte[tcp.Client.Available]; int resSize = ns.Read(rcvBytes, 0, rcvBytes.Length); if (sum == 0) { // 先頭の4バイトには、次に続くデータのサイズが書かれている bytes_to_read = ((ulong)rcvBytes[0]) | ((ulong)rcvBytes[1] << 8) | ((ulong)rcvBytes[2] << 16) | ((ulong)rcvBytes[3] << 24); Console.WriteLine("bytes_to_read = {0}", bytes_to_read); } sum += (ulong)resSize; ms.Write(rcvBytes, 0, resSize); } while (sum < bytes_to_read + 4); Console.WriteLine("size = {0}", (int)sum - 4); ms.Close(); String path = string.Format("full_{0}.jpg", adrs.ToString()); using (var fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite)) { fs.Write(ms.GetBuffer(), 4, (int)sum - 4); } ns.Close(); tcp.Close(); } mcastClient.Close(); }
internal static void Send(System.Net.Sockets.NetworkStream ns, PayLoad pl) { byte[] b = pl.GetPackage(); ns.Write(b, 0, b.Length); ns.Flush(); }
public static void Main() { string ipString = "127.0.0.1"; System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString); int port = 2001; System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(ipAdd, port); listener.Start(); Console.WriteLine("Listenを開始しました({0}:{1})。", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)listener.LocalEndpoint).Port); // 接続要求があったら受け入れる System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("クライアント({0}:{1})と接続しました。", ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port); // NetworkStreamを取得データの流れ System.Net.Sockets.NetworkStream ns = client.GetStream(); ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; System.Text.Encoding enc = System.Text.Encoding.UTF8; bool disconnected = false; System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; do { //データの一部を受信する resSize = ns.Read(resBytes, 0, resBytes.Length); //Readが0を返した時はクライアントが切断したと判断 if (resSize == 0) { disconnected = true; Console.WriteLine("クライアントが切断しました。"); break; } //受信したデータを蓄積する ms.Write(resBytes, 0, resSize); //まだ読み取れるデータがあるか、データの最後が\nでない時は、 // 受信を続ける } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); //受信したデータを文字列に変換 string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); resMsg = resMsg.TrimEnd('\n'); Console.WriteLine(resMsg); if (!disconnected) { //クライアントにデータを送信する //クライアントに送信する文字列を作成 string sendMsg = resMsg.Length.ToString(); //文字列をByte型配列に変換 byte[] sendBytes = enc.GetBytes(sendMsg + '\n'); //データを送信する ns.Write(sendBytes, 0, sendBytes.Length); Console.WriteLine(sendMsg); } ns.Close(); client.Close(); Console.WriteLine("クライアントとの接続を閉じました。"); listener.Stop(); Console.WriteLine("Listenerを閉じました。"); Console.ReadLine(); }
private async void MainWindow_Loaded(object sender, RoutedEventArgs e) { f.Navigate(sa); TcpClient tcp = new TcpClient(ipaddress, 2001); Console.WriteLine("サーバー({0}:{1})と接続しました({2}:{3})。", ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port); ns = tcp.GetStream(); //send name byte[] sendBytes = enc.GetBytes(name + '\n'); ns.Write(sendBytes, 0, sendBytes.Length); //サーバーから送られたデータを受信する await Task.Run(async() => { while (true) { string resMsg = await resGetAsync(); status_update(resMsg); if (resMsg.IndexOf("全員") > -1) { break; } await Task.Delay(100); } //ゲームスタート!! //Get namelist while (true) { string temp = await resGetAsync(); if (temp.IndexOf("namelist[") > -1) { Console.WriteLine(temp); int i = 0; MatchCollection mc = Regex.Matches(temp, @"\{(.+?)\}", RegexOptions.Singleline); foreach (Match m in mc) { string tem = m.ToString().Replace("{", "").Replace("}", "").Replace("\r\n", "").Replace("\n", ""); namelist[i++] = tem; } break; } await Task.Delay(100); } int cnt = 0; foreach (string s in namelist) { this.Dispatcher.Invoke(() => { if (s != name) { if (cnt == 0) { name1.Name = s; name1.Text = s + "[0]"; } else if (cnt == 1) { name2.Name = s; name2.Text = s + "[0]"; } else { name3.Name = s; name3.Text = s + "[0]"; } cnt++; } else { name_me.Name = name; name_me.Text = name + "[0]"; } }); } await this.Dispatcher.Invoke(async() => { sa.status.Text = "読み込んでいます"; for (int i = 1; i <= 13; i++) { clover[i - 1] = new BitmapImage(); clover[i - 1].BeginInit(); clover[i - 1].UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\clover\" + i.ToString() + ".png"); clover[i - 1].EndInit(); } for (int i = 1; i <= 13; i++) { heart[i - 1] = new BitmapImage(); heart[i - 1].BeginInit(); heart[i - 1].UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\heart\" + i.ToString() + ".png"); heart[i - 1].EndInit(); } for (int i = 1; i <= 13; i++) { spade[i - 1] = new BitmapImage(); spade[i - 1].BeginInit(); spade[i - 1].UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\spade\" + i.ToString() + ".png"); spade[i - 1].EndInit(); } for (int i = 1; i <= 13; i++) { dia[i - 1] = new BitmapImage(); dia[i - 1].BeginInit(); dia[i - 1].UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\dia\" + i.ToString() + ".png"); dia[i - 1].EndInit(); } joker.BeginInit(); joker.UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\joker.png"); joker.EndInit(); back.BeginInit(); back.UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\back.jpg"); back.EndInit(); await Task.Delay(1500); sa.status.Text = "ゲーム開始を待機しています"; sendMes("OKREADY"); //ゲーム開始を待機する string temp = await resGetAsync(); while (true) { if (temp.IndexOf("gamestart") > -1) { break; } await Task.Delay(500); } //カードを初期化 for (int i = 0; i < 14; i++) { mycardV[i] = -1; } //カード情報をゲット while (true) { if (temp.IndexOf("cardinfo") > -1) { mycard = temp; MatchCollection kmc = Regex.Matches(temp, @"\[(.+?)\]"); MatchCollection vmc = Regex.Matches(temp, @"\{(.+?)\}"); int mCnt = 0; int mmCnt = 0; foreach (Match m in kmc) { foreach (Match mm in vmc) { if (mCnt == mmCnt) { string ms = m.ToString().Replace("[", "").Replace("]", ""); string mms = mm.ToString().Replace("{", "").Replace("}", ""); Console.WriteLine(ms + mms); mycardK[mCnt] = ms; mycardV[mCnt] = int.Parse(mms); } mmCnt++; } mmCnt = 0; mCnt++; } mycardR = mCnt; break; } await Task.Delay(500); temp = await resGetAsync(); } { Image img = new Image(); img.Source = back; img.Width = 28; img.Height = 100; sp1.Children.Add(img); } { Image img = new Image(); img.Source = back; img.Width = 28; img.Height = 100; sp2.Children.Add(img); } { Image img = new Image(); img.Source = back; img.Width = 28; img.Height = 100; sp3.Children.Add(img); } status.Text = ""; }); while (true) { updateCard(); await Task.Delay(1000);//カードを更新してゲームを進行していきます } }); //閉じる ns.Close(); tcp.Close(); Console.WriteLine("切断しました。"); }
void toClientSend() { byte[] sendBytes = enc.GetBytes(ClientSendMsg + '\n'); ns.Write(sendBytes, 0, sendBytes.Length); }
static void Main(string[] args) { //Connect TcpClient tcpClient = new TcpClient(); tcpClient.Connect("localhost", 3334); MessageSender messageSender = new MessageSender(tcpClient.Session); MessageReceiver messageReceiver = new MessageReceiver(tcpClient.Session); MessageExecutor messageExecutor = new MessageExecutor(messageSender, messageReceiver, new InstantTaskScheduler()); messageExecutor.Configuration.DefaultTimeout = 10000; var notificationListener = new NotificationListener(); messageReceiver.AddListener(-1, notificationListener); //auth AuthorizeHciRequest request = new AuthorizeHciRequest(); request.ClientId = -1; request.Locale = "en-US"; var future = messageExecutor.Submit <AuthorizeHciResponse>(request); future.Wait(); AuthorizeHciResponse AuthorizeHciResponse = future.Value; int clientId = AuthorizeHciResponse.ClientId; System.Console.WriteLine("AuthorizeHciResponse precessed"); //login LoginRequest loginRequest = new LoginRequest(); loginRequest.UserLogin = "******"; loginRequest.UserPassword = "******"; loginRequest.ClientId = clientId; var loginResponcetask = messageExecutor.Submit <LoginResponse>(loginRequest); loginResponcetask.Wait(); // Id of the emu-copter is 2 var vehicleToControl = new Vehicle { Id = 3 }; TcpClientt.TcpListener server = new TcpClientt.TcpListener(IPAddress.Any, 8080); server.Start(); // run server byte[] ok = new byte[100]; ok = Encoding.Default.GetBytes("ok"); while (true) // бесконечный цикл обслуживания клиентов { TcpClientt.TcpClient client = server.AcceptTcpClient(); TcpClientt.NetworkStream ns = client.GetStream(); while (client.Connected) { byte[] msg = new byte[100]; int count = ns.Read(msg, 0, msg.Length); Console.Write(Encoding.Default.GetString(msg, 0, count)); string allMessage = Encoding.Default.GetString(msg); string result = allMessage.Substring(0, count - 1); var commandName = result.ToString().Split(":")[0]; switch (commandName) { case "takeoff_command": { Console.Write("got command: {0}", commandName); SendCommandRequest takeoff = new SendCommandRequest { ClientId = clientId, Command = new Command { Code = "takeoff_command", Subsystem = Subsystem.S_FLIGHT_CONTROLLER, Silent = true, ResultIndifferent = true } }; takeoff.Vehicles.Add(vehicleToControl); var takeoffCmd = messageExecutor.Submit <SendCommandResponse>(takeoff); takeoffCmd.Wait(); Thread.Sleep(5000); ns.Write(ok, 0, ok.Length); break; } case "direct_vehicle_control": { Console.Write("got command: {0}", commandName); var commandArgs = result.Split(":")[1]; Console.Write("args of command: {0}", commandArgs); // Vehicle control in joystick mode SendCommandRequest vehicleJoystickControl = new SendCommandRequest { ClientId = clientId, Command = new UGCS.Sdk.Protocol.Encoding.Command { Code = "direct_vehicle_control", Subsystem = Subsystem.S_FLIGHT_CONTROLLER, Silent = true, ResultIndifferent = true } }; vehicleJoystickControl.Vehicles.Add(vehicleToControl); List <CommandArgument> listJoystickCommands = new List <CommandArgument>(); var directionCommand = commandArgs.ToString().Split(",")[0]; string commandValueStr = commandArgs.ToString().Split(",")[1]; double commandValue = double.Parse(commandValueStr, System.Globalization.CultureInfo.InvariantCulture); switch (directionCommand) { case "roll": listJoystickCommands.Add(new CommandArgument { Code = "roll", Value = new Value() { DoubleValue = commandValue } }); listJoystickCommands.Add(new CommandArgument { Code = "pitch", Value = new Value() { DoubleValue = 0 } }); listJoystickCommands.Add(new CommandArgument { Code = "yaw", Value = new Value() { DoubleValue = 0 } }); listJoystickCommands.Add(new CommandArgument { Code = "throttle", Value = new Value() { DoubleValue = 0 } }); break; case "pitch": listJoystickCommands.Add(new CommandArgument { Code = "pitch", Value = new Value() { DoubleValue = commandValue } }); listJoystickCommands.Add(new CommandArgument { Code = "roll", Value = new Value() { DoubleValue = 0 } }); listJoystickCommands.Add(new CommandArgument { Code = "yaw", Value = new Value() { DoubleValue = 0 } }); listJoystickCommands.Add(new CommandArgument { Code = "throttle", Value = new Value() { DoubleValue = 0 } }); break; case "throttle": listJoystickCommands.Add(new CommandArgument { Code = "throttle", Value = new Value() { DoubleValue = commandValue } }); listJoystickCommands.Add(new CommandArgument { Code = "pitch", Value = new Value() { DoubleValue = 0 } }); listJoystickCommands.Add(new CommandArgument { Code = "roll", Value = new Value() { DoubleValue = 0 } }); listJoystickCommands.Add(new CommandArgument { Code = "yaw", Value = new Value() { DoubleValue = 0 } }); break; case "yaw": listJoystickCommands.Add(new CommandArgument { Code = "yaw", Value = new Value() { DoubleValue = commandValue } }); listJoystickCommands.Add(new CommandArgument { Code = "pitch", Value = new Value() { DoubleValue = 0 } }); listJoystickCommands.Add(new CommandArgument { Code = "roll", Value = new Value() { DoubleValue = 0 } }); listJoystickCommands.Add(new CommandArgument { Code = "throttle", Value = new Value() { DoubleValue = 0 } }); break; } vehicleJoystickControl.Command.Arguments.AddRange(listJoystickCommands); var sendJoystickCommandResponse = messageExecutor.Submit <SendCommandResponse>(vehicleJoystickControl); sendJoystickCommandResponse.Wait(); System.Console.WriteLine("Was sent {0}", commandValue); Thread.Sleep(2000); ns.Write(ok, 0, ok.Length); break; } case "set_relative_heading": { Console.Write("got command: {0}", commandName); var commandArgs = result.Split(":")[1]; Console.Write("args of command: {0}", commandArgs); // Vehicle control in joystick mode SendCommandRequest vehicleRelativeOffsetControl = new SendCommandRequest { ClientId = clientId, Command = new UGCS.Sdk.Protocol.Encoding.Command { Code = "set_relative_heading", Subsystem = Subsystem.S_FLIGHT_CONTROLLER, Silent = false, ResultIndifferent = false } }; vehicleRelativeOffsetControl.Vehicles.Add(vehicleToControl); List <CommandArgument> listRelativeOffsetCommands = new List <CommandArgument>(); var directionCommand = commandArgs.ToString().Split(",")[0]; string commandValueStr = commandArgs.ToString().Split(",")[1]; double commandValue = double.Parse(commandValueStr, System.Globalization.CultureInfo.InvariantCulture); switch (directionCommand) { case "relative_heading": listRelativeOffsetCommands.Add(new CommandArgument { Code = "relative_heading", Value = new Value() { DoubleValue = commandValue } }); break; } vehicleRelativeOffsetControl.Command.Arguments.AddRange(listRelativeOffsetCommands); var sendRelativeOffsetCommandResponse = messageExecutor.Submit <SendCommandResponse>(vehicleRelativeOffsetControl); sendRelativeOffsetCommandResponse.Wait(); System.Console.WriteLine("Was sent {0}", commandValue); Thread.Sleep(2000); ns.Write(ok, 0, ok.Length); break; } case "set_position_offset": { Console.Write("got command: {0}", commandName); var commandArgs = result.Split(":")[1]; Console.Write("args of command: {0}", commandArgs); // Vehicle control in joystick mode SendCommandRequest vehicleJoystickOffset = new SendCommandRequest { ClientId = clientId, Command = new UGCS.Sdk.Protocol.Encoding.Command { Code = "set_position_offset", Subsystem = Subsystem.S_FLIGHT_CONTROLLER, Silent = false, ResultIndifferent = false } }; vehicleJoystickOffset.Vehicles.Add(vehicleToControl); List <CommandArgument> listJoystickOffsetCommands = new List <CommandArgument>(); var directionCommand = commandArgs.ToString().Split(",")[0]; string commandValueStr = commandArgs.ToString().Split(",")[1]; double commandValue = double.Parse(commandValueStr, System.Globalization.CultureInfo.InvariantCulture); switch (directionCommand) { case "x": listJoystickOffsetCommands.Add(new CommandArgument { Code = "x", Value = new Value() { DoubleValue = commandValue } }); listJoystickOffsetCommands.Add(new CommandArgument { Code = "y", Value = new Value() { DoubleValue = 0 } }); listJoystickOffsetCommands.Add(new CommandArgument { Code = "z", Value = new Value() { DoubleValue = 0 } }); break; case "y": listJoystickOffsetCommands.Add(new CommandArgument { Code = "y", Value = new Value() { DoubleValue = commandValue } }); listJoystickOffsetCommands.Add(new CommandArgument { Code = "x", Value = new Value() { DoubleValue = 0 } }); listJoystickOffsetCommands.Add(new CommandArgument { Code = "z", Value = new Value() { DoubleValue = 0 } }); break; case "z": listJoystickOffsetCommands.Add(new CommandArgument { Code = "z", Value = new Value() { DoubleValue = commandValue } }); listJoystickOffsetCommands.Add(new CommandArgument { Code = "y", Value = new Value() { DoubleValue = 0 } }); listJoystickOffsetCommands.Add(new CommandArgument { Code = "x", Value = new Value() { DoubleValue = 0 } }); break; } vehicleJoystickOffset.Command.Arguments.AddRange(listJoystickOffsetCommands); var sendJoystickOffsetResponse = messageExecutor.Submit <SendCommandResponse>(vehicleJoystickOffset); sendJoystickOffsetResponse.Wait(); System.Console.WriteLine("Was sent {0}", commandValue); Thread.Sleep(2000); ns.Write(ok, 0, ok.Length); break; } case "payload_control": { Console.Write("got command: {0}", commandName); var commandArgs = result.ToString().Split(":")[1]; Console.Write("args of command: {0}", commandArgs); SendCommandRequest vehiclePayloadCommandRequest = new SendCommandRequest { ClientId = clientId, Command = new UGCS.Sdk.Protocol.Encoding.Command { Code = "payload_control", Subsystem = Subsystem.S_CAMERA, Silent = false, ResultIndifferent = false } }; vehiclePayloadCommandRequest.Vehicles.Add(vehicleToControl); List <CommandArgument> listPayloadCommands = new List <CommandArgument>(); var directionCommand = commandArgs.ToString().Split(",")[0]; string commandValueStr = commandArgs.ToString().Split(",")[1]; double commandValue = double.Parse(commandValueStr, System.Globalization.CultureInfo.InvariantCulture); switch (directionCommand) { case "tilt": listPayloadCommands.Add(new CommandArgument { Code = "tilt", Value = new Value() { DoubleValue = commandValue } }); listPayloadCommands.Add(new CommandArgument { Code = "roll", Value = new Value() { DoubleValue = 0 } }); listPayloadCommands.Add(new CommandArgument { Code = "yaw", Value = new Value() { DoubleValue = 0 } }); listPayloadCommands.Add(new CommandArgument { Code = "zoom_level", Value = new Value() { DoubleValue = 0 } }); break; case "roll": listPayloadCommands.Add(new CommandArgument { Code = "roll", Value = new Value() { DoubleValue = commandValue } }); listPayloadCommands.Add(new CommandArgument { Code = "tilt", Value = new Value() { DoubleValue = 0 } }); listPayloadCommands.Add(new CommandArgument { Code = "yaw", Value = new Value() { DoubleValue = 0 } }); listPayloadCommands.Add(new CommandArgument { Code = "zoom_level", Value = new Value() { DoubleValue = 0 } }); break; case "zoom_level": listPayloadCommands.Add(new CommandArgument { Code = "zoom_level", Value = new Value() { DoubleValue = commandValue } }); listPayloadCommands.Add(new CommandArgument { Code = "tilt", Value = new Value() { DoubleValue = 0 } }); listPayloadCommands.Add(new CommandArgument { Code = "roll", Value = new Value() { DoubleValue = 0 } }); listPayloadCommands.Add(new CommandArgument { Code = "yaw", Value = new Value() { DoubleValue = 0 } }); break; case "yaw": listPayloadCommands.Add(new CommandArgument { Code = "yaw", Value = new Value() { DoubleValue = commandValue } }); listPayloadCommands.Add(new CommandArgument { Code = "tilt", Value = new Value() { DoubleValue = 0 } }); listPayloadCommands.Add(new CommandArgument { Code = "roll", Value = new Value() { DoubleValue = 0 } }); listPayloadCommands.Add(new CommandArgument { Code = "zoom_level", Value = new Value() { DoubleValue = 0 } }); break; } vehiclePayloadCommandRequest.Command.Arguments.AddRange(listPayloadCommands); var sendPayloadCommandResponse = messageExecutor.Submit <SendCommandResponse>(vehiclePayloadCommandRequest); sendPayloadCommandResponse.Wait(); System.Console.WriteLine("Was sent {0}", commandValue); Thread.Sleep(2000); ns.Write(ok, 0, ok.Length); break; } case "land_command": { SendCommandRequest land = new SendCommandRequest { ClientId = clientId, Command = new UGCS.Sdk.Protocol.Encoding.Command { Code = "land_command", Subsystem = Subsystem.S_FLIGHT_CONTROLLER, Silent = false, ResultIndifferent = false } }; land.Vehicles.Add(vehicleToControl); var landCmd = messageExecutor.Submit <SendCommandResponse>(land); landCmd.Wait(); Thread.Sleep(5000); ns.Write(ok, 0, ok.Length); break; } case "joystick": { SendCommandRequest joystickModeCommand = new SendCommandRequest { ClientId = clientId, Command = new UGCS.Sdk.Protocol.Encoding.Command { Code = "joystick", Subsystem = Subsystem.S_FLIGHT_CONTROLLER, Silent = false, ResultIndifferent = false } }; joystickModeCommand.Vehicles.Add(vehicleToControl); var joystickMode = messageExecutor.Submit <SendCommandResponse>(joystickModeCommand); joystickMode.Wait(); ns.Write(ok, 0, ok.Length); break; } case "manual": { break; } } } // System.Console.ReadKey(); // tcpClient.Close(); // messageSender.Cancel(); // messageReceiver.Cancel(); // messageExecutor.Close(); // notificationListener.Dispose(); } }
// Update is called once per frame void Update() { //↓にC++に送るデータをぶち込む //今回は経過時間 if (goldfish0.moterflag == 1 || goldfish1.moterflag == 1 || goldfish2.moterflag == 1 || goldfish3.moterflag == 1 || goldfish4.moterflag == 1) { data = "1"; } else { data = "0"; } //Debug.Log(goldfish0.moterflag.ToString()); //data = "1.0000"; //data = Time.time.ToString(); //タイムアウト設定 ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; //サーバーにデータを送信 //文字列をByte型配列に変換 System.Text.Encoding enc = System.Text.Encoding.UTF8; byte[] sendBytes = enc.GetBytes(data + '\n'); //データを送信する ns.Write(sendBytes, 0, sendBytes.Length); //Debug.Log(data); //サーバーから送られたデータを受信する //今回は一周期分の時間が送られてくる。 System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 256; //データを受信 resSize = ns.Read(resBytes, 0, resBytes.Length); //受信したデータを蓄積 ms.Write(resBytes, 0, resSize); //受信したデータを文字列に変換 resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); //末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); //Debug.Log(resMsg); //データをセンサの数だけ分割 string[] str = resMsg.Split(' '); for (int i = 0; i < str.Length; i++) { //int型に変換 num[i] = int.Parse(str[i]); //Debug.Log(num[i]); } //書き込みを行うセンサー値を取得 /* * SenserVal[SenserCount] = num[1]; * Debug.Log(SenserVal[SenserCount]); * SenserCount += 1; */ //rb.MoveRotation(Quaternion.AngleAxis(45f, Vector3.forward))Debug.Log(num); //スペース押すと閉じる if (Input.GetKey(KeyCode.Space)) { //センサー値をCSV形式でエクスポート //logSave(SenserVal, "Test"); ns.Close(); tcp.Close(); Debug.Log("切断しました。"); } }
public static void Main() { // ListenするIPアドレス string ipString = "127.0.0.1"; System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString); // Listenするポート番号 int port = 2001; // TcpListenerオブジェクトの作成 System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(ipAdd, port); // Listenを開始 listener.Start(); Console.WriteLine("Listenを開始しました({0}:{1}).", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)listener.LocalEndpoint).Port); // 接続要求があったら受け入れる System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("クライアント({0}:{1})と接続しました.", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)listener.LocalEndpoint).Port); // NetworkStreamを取得 System.Net.Sockets.NetworkStream ns = client.GetStream(); // 読取り,書き込みのタイムアウトを10秒にする // デフォルトはInfiniteでタイムアウトしない // (.NET Framework 2.0以上が必要 ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; // クライアントから送られたデータを受信する System.Text.Encoding enc = System.Text.Encoding.UTF8; bool disconnected = false; System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; do { // データの一部を受信する resSize = ns.Read(resBytes, 0, resBytes.Length); // Readが0を返した時はクライアントが切断したと判断 if (resSize == 0) { disconnected = true; Console.WriteLine("クライアントが切断しました."); break; } // 受信したデータを蓄積する ms.Write(resBytes, 0, resSize); // まだ読み取れるデータがあるか,データの最後が\n出ない時は,受信を続ける } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); // 受信したデータを文字列に変換 string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); // 末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); Console.WriteLine(resMsg); if (!disconnected) { // クライアントにデータを送信する // クライアントに送信する文字列を作成 string sendMsg = resMsg.Length.ToString(); // 文字列をByte型配列に変換 byte[] sendBytes = enc.GetBytes(sendMsg + "\n"); // データを送信する ns.Write(sendBytes, 0, sendBytes.Length); Console.WriteLine(sendMsg); } // 閉じる ns.Close(); client.Close(); Console.WriteLine("クライアントとの接続を閉じました."); // リスナを閉じる listener.Stop(); Console.WriteLine("Listenerを閉じました."); Console.ReadLine(); }