I'm working in a code that come from C# and I'm trying to traduce it in java. Basically in first step I send and receive some data-command to an IP camera through TCP (this is done) and in second step I have to receive the image through UDP. The problem is with second step: receive image from UDP. I try every code in internet but no one work.
The originally code in C# is this:
*Example to server connection in C#
Socket _ServerUdp = null;
Socket _ServerTcpIp = null;
IPEndPoint _EndpointUdp = null;
TcpClient _ClientUdp;
/// <summary>
/// Connect the socket
/// <summary>
public bool Connect(string IpAddr)
{
if (!_VideoPortConnect(IpAddr, 8501))
return false;
if (!_CommandPortConnect(IpAddr, 8500))
return false;
return true;
}
/// <summary>
/// Udp Connect
/// </summary>
bool _VideoPortConnect(string IpAddr, int VideoPort)
{
try
{
_ServerUdp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_EndpointUdp = new IPEndPoint(IPAddress.Parse(IpAddr), VideoPort);
_ClientUdp = new TcpClient();
_ClientUdp.Connect(_EndpointUdp);
return true;
}
catch { return false; }
}
/// <summary>
/// Tcp Ip Connect
/// </summary>
bool _CommandPortConnect(string IpAddr, int CommandPort)
{
_ServerTcpIp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint _RemoteEndPoint = new IPEndPoint(IPAddress.Parse(IpAddr), CommandPort);
_ServerTcpIp.ReceiveTimeout = 5000;
_ServerTcpIp.SendTimeout = 5000;
try
{
_ServerTcpIp.Connect(_RemoteEndPoint);
return true;
}
catch { return false; }
*}*
Example for send command and receive image The command will be send by TCP/IP.
byte[] DataReceived = new byte[20000];
/// <summary>
/// Send Command Bar Code Reader
/// </summary>
/// <returns></returns>
bool SendCommand()
{
byte[] _Send = new byte[3];
_Send[0]= 20; //CMD BAR CODE READER
_Send[1] = 2; //EXT CMD GET DATA
_Send[2] = 2; //SEND IMAGE
if (!SendEth(_Send, 3))
return false;
int _Ndati = ReadEth();
if (_Ndati == -1)
return false;
if (DataReceived[4] != 20)
return false;
GetImage();
}
/// <summary>
/// Send Data
/// </summary>
/// <param name="_Val"></param>
/// <param name="_Len"></param>
bool SendEth(byte[] _Val, Int32 _Len)
{
try
{
byte[] _Send = new byte[_Len + 4];
int _Value = _Len;
Array.Copy(_Val, 0, _Send, 4, _Len);
_Send[3] = (byte)_Value;
_Value <<= 8;
_Send[2] = (byte)_Value;
_Value <<= 8;
_Send[1] = (byte)_Value;
_Value <<= 8;
_Send[0] = (byte)_Value;
_ServerTcpIp.Send(_Send, _Len + 4, SocketFlags.None);
}
catch { return false; }
return true;
}
/// <summary>
/// Read Data from Ethernet
/// </summary>
/// <param name="LenDati"></param>
/// <returns>array dati</returns>
internal int ReadEth()
{
int _Ndati;
try
{
_Ndati = _ServerTcpIp.Receive(DataReceived, SocketFlags.None);
DataPointer =0;
int _Len = GetInt();
if(_Len!=_Ndati-4)
{
int _Diff = (_Ndati - 4) - _Len;
byte[] BuffRx = new byte[_Diff];
int _NrDati = 0;
int _PuntRx = _Ndati;
while (_PuntRx < _Diff)
{
_NrDati = _ServerTcpIp.Receive(BuffRx, _Diff, SocketFlags.None);
for (int n = 0; n < _NrDati; n++)
DataReceived[_PuntRx++] = BuffRx[n];
}
}
return _Ndati;
}
catch { return -1; }
}
/// <summary>
/// Get Image
/// </summary>
/// <returns></returns>
internal ImageSource GetImage()
{
//get image
NetworkStream _Stream = _ClientUdp.GetStream();
byte[] _Data = (byte[])_Formatter.Deserialize(_Stream);
MemoryStream _ImgStream = new MemoryStream(_Data);
ImageSource _Image = BitmapFrame.Create(_ImgStream, BitmapCreateOptions.None,
BitmapCacheOption.OnLoad);
return _Image;
}
My JAVA code:
public class TFinale {
static byte[] DataReceived = new byte[20000];
public static void main(String[] args) throws Exception {
String[] args8500 = new String[2];
args8500[0] = "10.0.0.123";
args8500[1] = "8500";
int port8500 = Integer.parseInt(args8500[1]);
String[] args8501 = new String[2];
args8501[0] = "10.0.0.123";
args8501[1] = "8501";
int port8501 = Integer.parseInt(args8501[1]);
Socket clientSocket8501 = TFinale.createSocket(args8501[0], port8501);
if (clientSocket8501 == null) {
System.err.println("Unable to create socket to " + args8501[0] + ":" + port8501 + ".");
System.exit(1);
}
Socket clientSocket8500 = TFinale.createSocket(args8500[0], port8500);
if (clientSocket8500 == null) {
System.err.println("Unable to create socket to " + args8500[0] + ":" + port8500 + ".");
System.exit(1);
}
byte[] _Send = new byte[3];
_Send[0] = 22; //CMD BAR CODE READER
_Send[1] = 2; //EXT CMD GET DATA
_Send[2] = 2; //SEND IMAGE
int _Len1 = 3;
byte[] SendEth1 = SendEth(_Send, _Len1);
DataOutputStream serverOut = null;
try {
serverOut = new DataOutputStream(clientSocket8500.getOutputStream());
serverOut.write(SendEth1, 0, 7);
System.out.println("serverOut writed!");
} catch (IOException ex) {
Logger.getLogger(TFinale.class.getName()).log(Level.SEVERE, null, ex);
}
DataInputStream in = null;
try {
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
in = new DataInputStream(clientSocket8500.getInputStream());
int bytesRead = 0;
int f = 0;
//System.out.println("Please type 8500 clientSocket......");
for (f = 0; f < 7; f++) {
messageByte[f] = in.readByte();
System.out.println("messageByte 8500[" + f + "] " + messageByte[f]);
}
ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, f);
int bytesToRead = byteBuffer.getShort();
System.out.println("About to read " + bytesToRead + " octets");
} catch (IOException ex) {
Logger.getLogger(TCPClient1.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
in.close();
} catch (IOException ex) {
Logger.getLogger(TCPClient1.class.getName()).log(Level.SEVERE, null, ex);
}
}
timeDelay(1000);
try {
serverOut.close();
System.out.println("serverOut closed!");
in.close();
System.out.println("in closed!");
clientSocket8501.close();
System.out.println("clientSocket8501 closed!");
clientSocket8500.close();
System.out.println("clientSocket8500 closed!");
} catch (IOException ex) {
System.out.println("error:" + ex);
}
}
private static Socket createSocket(final String hostname, final int port) {
try {
Socket clientSocket = new Socket(hostname, port);
System.out.println(hostname + ":" + port + " socket created!");
return clientSocket;
} catch (UnknownHostException e) {
System.err.println(" " + hostname + " cannot be resolved as a network host.");
return null;
} catch (IOException e) {
System.err
.println("An exception occurred while communicating with the TCPServer: "
+ e.getMessage());
e.printStackTrace();
return null;
}
}
private static void timeDelay(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
}
}
private static byte[] SendEth(byte[] _Val, int _Len) {
byte[] _Send = new byte[_Len + 4];
int _Value = _Len;
System.arraycopy(_Val, 0, _Send, 4, _Len);
//Array.Copy(_Val, 0, _Send, 4, _Len);
_Send[3] = (byte) _Value;
_Value <<= 8;
_Send[2] = (byte) _Value;
_Value <<= 8;
_Send[1] = (byte) _Value;
_Value <<= 8;
_Send[0] = (byte) _Value;
return _Send;
}
}
Thanks everybody can help me!
@Federico111,您应该使用java.net.DatagramSocket
而不是Socket
来处理 UDP。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.