UDP client bug - Unable to send data bytes - c#

I am writting a C# P2P Video Chat (Part of my exam on Faculty),a i am little stuck at send Data via udp. So here how it works. I have a Web_Capture library, and every time image is captured it sets PictureBox image to the captured one
private void webCamCapture_ImageCaptured(object source, WebCam_Capture.WebcamEventArgs e)
{
myCamera.Image = e.WebCamImage;
sendData(ref ipep2); // send it immediately
}
So then the sendData method starts sending...
private void sendData(ref IPEndPoint sender)
{
byte[] data;
if (friendsClient == null)
{
friendsClient = new UdpClient();
}
MemoryStream myStream = new MemoryStream();
myCamera.Image.Save(myStream, System.Drawing.Imaging.ImageFormat.Jpeg);
data = myStream.GetBuffer();
friendsClient.Send(data, data.Length,sender);
}
When i debug, the socket exception pops out:
System.Net.Sockets.SocketException was unhandled by user code
Message=The requested address is not valid in its context
Source=System
ErrorCode=10049
NativeErrorCode=10049
So, does anyone have any idea, i will be thankfull if he support that idea with code, because i am nooby at c# :) thanks in advance. Marjan

You should specify reciever's ip and port, Here is a complete example
so you should change your implementation to
private void sendData(ref IPEndPoint reciever)
{
byte[] data;
Socket sending_socket = new Socket(AddressFamily.InterNetwork, ocketType.Dgram, ProtocolType.Udp);
MemoryStream myStream = new MemoryStream();
myCamera.Image.Save(myStream, System.Drawing.Imaging.ImageFormat.Jpeg);
data = myStream.GetBuffer();
sending_socket.SendTo(data, reciever);
}

Related

How to receive continuous images using UDP C#

I am trying to develop an video chat application via UDP C#. I have an picture box that shows the webcam of the user continuously and sending to a specific port. But I don't know how to receive the Image
I am using a byte to image / image to byte converter class (which normally works fine) but when I put this code in a timer sequence I get this error
'A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself'
here is my code :
private void timer1_Tick(object sender, EventArgs e)
{
Image bitmap = pictureBox1.Image;
byte[] sndcam = imageToByteArray(bitmap);
string Ip = "127.0.0.1";
int port = 1111;
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(Ip), port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.SendTo(sndcam, ep);
}
I've seen few questions like this on Stackoverflow but I cloudn't find a satisfying answer
Should I use RTP instead ? If so , How ?
Thanks in advance

How to send JPG over TCP from one Windows Phone to another? I already managed sending text

How to send JPG over TCP from one Windows Phone to another?
I found that in the other SO topic(below) showing how to send text over TCP, but how to turn JPG to bytes and send it? Most of jpges are bigger than 4kb how to deal with that?:
private void sendMessage() {
connectArgs = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint(localIP, Int32.Parse(port)) };
connectArgs.Completed += connectArgs_Completed;
connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connection.ConnectAsync(connectArgs);
}
void connectArgs_Completed(object sender, SocketAsyncEventArgs e) {
if (e.SocketError == SocketError.Success && firstLoop) {
firstLoop = false;
var sendArgs = new SocketAsyncEventArgs();
var buffer = Encoding.UTF8.GetBytes("MESSAGE STRING" + Environment.NewLine);
sendArgs.SetBuffer(buffer, 0, buffer.Length);
sendArgs.Completed += sendArgs_Completed;
e.ConnectSocket.SendAsync(sendArgs);
} else {
//blad
}
}
You should probably read the raw image data and send that, along with a special "code" or prefix, and then on the receiving end, save the raw image data to a .jpg file and display that. You can do that with any file.
TCP doesn't limit the size of the packets to 4KB, so that shouldn't be a problem for you. You simply need to read all the image bytes either from file using File.ReadAllBytes or a stream reader, and you then send those bytes across to the receiver.
Alternatively, if you have the image as an object, you could use Marshal.StructureToPtr on the sending end and then use Marshal.PtrToStructure to re-create the image object from the bytes you have received, if you want to show the image directly for example.

.Net isn't deserializing stream when sent from Websockets

I'm making an application in PhoneGap, and I'm using HTML5 Websockets to send some info to another device (read: sending data to another user who has the app). Users are registered with ID and Username.
For this, I read that I have to make an TCP/Socket connection. I've tried to use an old socket-chat I once made in school with C#.
I'm connecting to the socket this way from the app:
var ws = new WebSocket("ws://127.0.0.1:7001");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("message");
};
And the server side looks like this (of course isn't the entire code, but the relevant parts)
private NetworkStream stream;
private IFormatter formatter = new BinaryFormatter();
private TcpListener server;
public TcpClient client;
private string username { get; set; }
private void StartServer()
{
int port = Convert.ToInt32(portUser);
server = new TcpListener(IPAddress.Parse(IP), port);
server.Start();
client = server.AcceptTcpClient();
stream = client.GetStream();
username = formatter.Deserialize(stream).ToString();
}
The last deserialize-line writes:
The input stream is not a valid binary format. The starting contents (in bytes) are: 47-45-54-20-2F-20-48-54-54-50-2F-31-2E-31-0D-0A-48 ...
Any other way to deserialize the stream? Or am I using a completely wrong way?
Edit: working C# way I used to send data between clients in the chatter
stream = client.GetStream();
formatter.Serialize(stream, messageobj);
stream.Flush();

Socket writing not working properly c#

I'm working on a biometry system with my C# application.
Sdk provices a connection via TCP/IP on port 2100, and works by receiving and sending strings to communicate .
My class:
class Biometry
{
private System.Net.Sockets.TcpClient _clientSocket = new System.Net.Sockets.TcpClient();
public Biometry() {
//connect to socket
_clientSocket.Connect("127.0.0.1", 2100);
_clientSocket.ReceiveTimeout = 9000;
}
public String identify(String msg) {
//get network stream
NetworkStream _serverStream = _clientSocket.GetStream();
//send an array of bites that represents a string(encoded)
System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(msg);
_serverStream.Write(outStream, 0, outStream.Length);
//reads the response from networkStream
byte[] inStream = new byte[10025];
_serverStream.Read(inStream, 0, (int)_clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
_serverStream.Close();
return returndata;
}
}
The problem is:
It is not working!! The biometry only works(SDK only understand my request) when I close the application(connection is closed).
You might need to flush the stream before your start reading using _serverStream.Flush().
Another problem might be that in your question you say you need to connect to port 21000, but in your code you connect to 2100, which might be a typo in either place, but should be fixed ;-)
In addition to flushing the stream, your server might also be waiting for an "end of message" indicator?

Cannot receive Image over TCP socket?

I have problem with receiving an image over TCP socket [.net 4.0]
Server:
Socket s = null;
Socket client;
private void button1_Click(object sender, EventArgs e)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(new IPEndPoint(IPAddress.Any, 9988));
s.Listen(1);
client = s.Accept();
pictureBox1.Image = Image.FromStream(new NetworkStream(client));
//Server freezes here and waiting for the image .. but in the Client side.. it tells that it sent.
Console.WriteLine("Received.");
}
Client:
Socket s = null;
private void button1_Click(object sender, EventArgs e)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9988));
Rectangle bounds = Screen.GetBounds(Point.Empty);
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);
Graphics g = Graphics.FromImage(bitmap);
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
bitmap.Save(new NetworkStream(s), ImageFormat.Png);
Console.WriteLine("sent.");
}
Edit:
im making a big application .. image was receiving just fine .. then i did some changes on the code so it got complicated to know what did i exactly change .. now it's not working .. so i made new projects and tried the code up.. still doesn't work .. i know that there's another ways to do it.. but i prefer to do this way.
Anyone knows how to fix it ??
i think you need to convert the image to byte and then get the byte's size and send it to the server, the server prepares the buffer size and then the client send the image's bytes, you can find s video on how to do it Right Here
Most probably you need to close the socket after sending the data.
Image.FromStream() probably waits until the NetworkStream indicates there are no more bytes to process, but since you declared the Socket on the form's class level, it stays connected and the server waits for more data.

Categories

Resources