I am trying to login Ericsson MD110 alex through the c# application. The md110 returned values that asking the username for login the application, but once I pass the username and password through the following code:
public static void Main(string[] args)
{
try
{
byte[] data = new byte[1024];
string stringData;
//TcpClient tcpclnt = new TcpClient();
//Console.WriteLine("Connecting.....");
string ipaddress = "192.168.1.30";
int port=23;
IPAddress ipadd = IPAddress.Parse(ipaddress);
IPEndPoint ipend = new IPEndPoint(ipadd, port);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.NoDelay = false;
sock.Connect(ipend);
//recive data
int recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
//textBox4.AppendText(stringData + "\r\n");
Console.Write(stringData);
//while (true)
//{
Byte[] bBuf;
string buf;
//Application.DoEvents();
//buf = String.Format("{0}\r\n{1}\r\n", "MDUSER", "HELP");
buf = String.Format("ALREI;");
//buf = string.Format("ENTER USER NAME<.MDUSER;MDUSER;ENTER PASSWORD<.HELP;");
bBuf = Encoding.ASCII.GetBytes(buf);
sock.Send(bBuf);
data = new byte[1024];
recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
//textBox4.AppendText(stringData + "\r\n");
string df = "";
Console.Write(stringData);
Console.ReadLine();
//}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
Console.ReadKey();
}
}
Further, I checked with wireshark, but md110 doesn't return any value.
only acknowledge data packet will receive.
I need some advice.
Related
I am trying to create a simple proxy server(very simple, doesn't even cache everything) that swaps contents(words, Images, and href) from the reply of origin and forward back to the client. (A proxy server that sends "Fake News" to the client).
I can change every occurrence of "Cat" into "Dog" and every occurrence of "Moon" to "Sun", but I don't know how to swaps the images and hrefs.
Thank you!
public class GetHttp {
public static String extractHost(String request) {
String[] tokens = request.split("\n");
String url = tokens[1].split(" ")[1];
return url;
}
public static byte[] replaceContext(byte[] message) {
String toReturn = new String(message);
// Here is the problem: I don't know how to swap href and images.
//toReturn = toReturn.replaceAll("<img src=\"This is a place holder\"","<img src=\"This is a place holder\" width");
//toReturn = toReturn.replaceAll("<a href=\"This is a place Holder\">", "<a href=\"This is a place Holder\">");
toReturn = toReturn.replaceAll("Cat", "Dog");
toReturn = toReturn.replaceAll("Moon", "Sun");
System.out.println(toReturn);
);
return toReturn.getBytes();
}
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(8888);
while (true) {
Socket connectionSocket = server.accept();
BufferedInputStream inFromClient = new BufferedInputStream(connectionSocket.getInputStream());
// Server reads the HTTP request
byte[] buffer = new byte[8192];
inFromClient.read(buffer);
String clientRequest = new String(buffer);
String originName = extractHost(clientRequest);
// Create the http request from server to the origin
Socket origin = new Socket(InetAddress.getByName(originName.trim()), 80);
BufferedOutputStream outToOrigin = new BufferedOutputStream(origin.getOutputStream());
outToOrigin.write(clientRequest.getBytes());
outToOrigin.flush();
// receive the content from origin
// return back to the client
BufferedInputStream inFromOrigin = new BufferedInputStream(origin.getInputStream());
buffer = new byte[8192];
int buffersize = 0;
BufferedOutputStream outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
while ((buffersize=inFromOrigin.read(buffer)) != -1) {
byte[] temp = new byte[buffersize];
for(int i=0;i<buffersize;i++){
temp[i] = buffer[i];
}
// swap the context
outToClient.write(replaceContext(temp));// ,0,buffsize);
}
outToClient.flush();
outToOrigin.close();
inFromOrigin.close();
inFromClient.close();
outToClient.close();
origin.close();
connectionSocket.close();
}
}
}
I wrote a server and client for client to connect to the server and select a data from the server's directory to transfer the data with UDP protocol but the problem is, it is only working for .txt files it isn't working for .png files and also in the .txt files the output files are not the same with the original one forexample lines between words are not there and all the words printed side by side instead of line by line. How can i fix this problem ?
Server side:
import java.io.*;
import java.net.*;
public class FTPServer {
public static void main(String[] args)
{
DatagramSocket socket = null;
DatagramPacket inPacket = null;
DatagramPacket outPacket = null;
byte[] inBuf, outBuf;
String msg;
final int PORT = 50000;
try
{
socket = new DatagramSocket(PORT);
while(true)
{
System.out.println("\nRunning...\n");
inBuf = new byte[1000];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
int source_port=inPacket.getPort();
InetAddress source_address = inPacket.getAddress();
msg = new String(inPacket.getData(), 0, inPacket.getLength());
System.out.println("CLient: " + source_address + ":" + source_port);
String dirname = "/home/erke/Desktop/data";
File f1 = new File(dirname);
File fl[] = f1.listFiles();
StringBuilder sb = new StringBuilder("\n");
int c=0;
for(int i = 0;i<fl.length;i++)
{
if(fl[i].canRead())
c++;
}
sb.append(c+ " files found.\n\n");
for(int i=0; i<fl.length;i++)
sb.append(fl[i].getName()+ " " + fl[i].length()+ " Bytes\n");
sb.append("\nEnter file name to Download: ");
outBuf = (sb.toString()).getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length, source_address, source_port);
socket.send(outPacket);
inBuf = new byte[1000];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
String filename = new String(inPacket.getData(), 0, inPacket.getLength());
System.out.println("Requested File: " + filename);
boolean flis = false;
int index =-1;
sb = new StringBuilder("");
for(int i=0;i<fl.length;i++)
{
if(((fl[i].getName()).toString()).equalsIgnoreCase(filename))
{
index = i;
flis = true;
}
}
if(!flis)
{
System.out.println("ERROR");
sb.append("ERROR");
outBuf = (sb.toString()).getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length, source_address, source_port);
socket.send(outPacket);
}
else
{
try
{
//File send
File ff=new File(fl[index].getAbsolutePath());
FileReader fr = new FileReader(ff);
BufferedReader brf = new BufferedReader(fr);
String s = null;
sb=new StringBuilder();
while((s=brf.readLine())!=null)
{
sb.append(s);
}
if(brf.readLine()==null)
System.out.println("File Read Succesfull, CLosing Socket");
outBuf=new byte[100000];
outBuf = (sb.toString()).getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length,source_address, source_port);
socket.send(outPacket);
} catch (Exception ioe) {
System.out.println(ioe);
}
}
}
} catch (Exception e){
System.out.println("Error\n");
}
}
}
Client side:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class FTPClient {
public static void main(String[] args) {
DatagramSocket socket = null;
DatagramPacket inPacket = null;
DatagramPacket outPacket = null;
byte[] inBuf, outBuf;
final int PORT = 50000;
String msg = null;
Scanner src = new Scanner(System.in);
try
{
InetAddress address = InetAddress.getByName("127.0.0.1");
socket = new DatagramSocket();
msg = "";
outBuf =msg.getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length,address,PORT);
socket.send(outPacket);
inBuf = new byte[65535];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
String data = new String(inPacket.getData(), 0, inPacket.getLength());
//Print file list
System.out.println(data);
//Send file name
String filename = src.nextLine();
outBuf = filename.getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length, address, PORT);
socket.send(outPacket);
//Receive file
inBuf = new byte[100000];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
data = new String(inPacket.getData(), 0, inPacket.getLength());
if(data.endsWith("ERROR"))
{
System.out.println("File doesn't exists.\n");
socket.close();
}
else
{
try
{
BufferedWriter pw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)));
pw.write(data);
//Force write buffer to Fİle
pw.close();
System.out.println("File Write Succesful. Closing Socket");
socket.close();
} catch (Exception ioe) {
System.out.println("File Error\n");
socket.close();
}
}
} catch (Exception e) {
System.out.println("\nNetwork Error. Try Again Later. \n");
}
}
}
In your code you are using String to store file data in both client and the server. In order to be able to transfer any file other then a text file, in your server you should have a byte[] buffer instead of String, and use it for loading file contents. You can do this by using classes with names ending with InputStream. After you do that send those bytes over a network. Same goes for the client.
InputStream and OutputStream are used to read\write bytes from files directly, while Reader and Writer classes are specifically intended to work with text files. You cannot read\write bytes with these classes, they work only with characters and strings. You will still be able to transfer text files too though since they are also just an array of bytes.
Also you should be using TCP if you want to transfer your files without losing packets, which UDP tends to do as it doesn't have mechanisms to ensure that packets are safely delivered to a destination like TCP does.
Hi there I am new to java and network programming... I am trying to send two UDP packets from (AssignmentChatClient) to a server (AssignmentChatServer), the server will check the first packet which contains (IP address of destination) and then forward the second packet (message) to the destination (AssignmentChatClient2). I have a problem that the destination (AssignmentChatClient2) does not receive the packet... Could you guys help me to point out where the problem is ? Thanks in advance...
Here is the code
AssignmentChatServer
import java.net.*;
import java.io.*;
public class AssignmentChatServer {
public static void main(String args[]) throws IOException {
int sPort = 2222, cPort = 3333;
byte[] buf = null;
byte[] buf2 = null;
System.out.println("Listening to socket port " + sPort);
try (DatagramSocket serverSocket = new DatagramSocket(sPort)) {
while (true) {
buf = new byte[128];
buf2 = new byte [1024];
String addr = "";
String sMsg = "";
char [] tempC = null;
DatagramPacket addrPacket = null;
DatagramPacket msgPacket = null;
addrPacket = new DatagramPacket(buf, buf.length);
serverSocket.receive(addrPacket);
String address = new String(addrPacket.getData()).trim();
System.out.println(address);
tempC = address.toCharArray();
for(int i = 0; i < tempC.length; i++){
if(tempC[i] == '-'){
InetAddress sAddr = InetAddress.getByName(addr);
msgPacket = new DatagramPacket(buf2, buf2.length);
serverSocket.receive(msgPacket);
String msg = new String(msgPacket.getData());
sMsg = msg.trim();
msgPacket = new DatagramPacket(sMsg.getBytes(),sMsg.getBytes().length, sAddr, cPort);
serverSocket.send(msgPacket);
System.out.println(sMsg);
addr = "";
continue;
}
addr += tempC[i];
}
}
}catch(IOException ex){System.out.println(ex);}
}
}
AssignmentChatClient
import java.net.*;
import java.io.*;
public class AssignmentChatClient {
public static void main(String args[]) throws IOException {
int sPort = 2222, cPort = 3333;
byte[] buf = null;
byte[] buf2 = null;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter server address : ");
String serAddress = input.readLine();
InetAddress sAddr = InetAddress.getByName(serAddress);
System.out.println("Connecting to server socket on port " + sPort);
try (DatagramSocket clientSocket = new DatagramSocket(cPort)) {
while (true) {
buf = new byte[128];
buf2 = new byte [1024];
String temp = "";
String sMsg = "";
String rMsg = "";
DatagramPacket addrPacket = null;
DatagramPacket rlyPacket = null;
DatagramPacket msgPacket = null;
System.out.print("How many the number of users do you want to send to : ");
int nUsers = Integer.parseInt(input.readLine());
byte [] address = new byte [nUsers];
address = null;
System.out.print("Enter message : ");
sMsg = input.readLine();
if(sMsg == null)
return ;
for(int i = 0, j = 0; i < nUsers ; i++){
System.out.print("Please enter address " + ++j + " : ");
temp += input.readLine();
temp += "-";
}
address = temp.getBytes();
addrPacket = new DatagramPacket(address,address.length, sAddr, sPort);
clientSocket.send(addrPacket);
// System.out.println(temp);
msgPacket = new DatagramPacket(sMsg.getBytes(),sMsg.getBytes().length, sAddr, sPort);
clientSocket.send(msgPacket);
// System.out.println(sMsg);
// System.out.println(sAddr.toString());
rlyPacket = new DatagramPacket(buf2, buf2.length);
clientSocket.receive(rlyPacket);
String msg = new String(rlyPacket.getData());
rMsg = msg.trim();
System.out.println(rMsg);
}
}catch(IOException ex){System.out.println(ex);}
}
}
AssignmentChatClient2
import java.net.*;
import java.io.*;
public class AssignmentChatClient2 {
public static void main(String args[]) throws IOException {
int sPort = 2222, cPort = 3333;
byte[] buf = null;
byte[] buf2 = null;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter server address : ");
String serAddress = input.readLine();
InetAddress sAddr = InetAddress.getByName(serAddress);
System.out.println("Connecting to server socket on port " + sPort);
try (DatagramSocket clientSocket = new DatagramSocket(cPort)) {
while (true) {
buf2 = new byte [1024];
String temp = "";
String replyMsg = "";
String rMsg = "";
DatagramPacket addrPacket = null;
DatagramPacket rcvPacket = null;
DatagramPacket msgPacket = null;
rcvPacket = new DatagramPacket(buf2, buf2.length);
clientSocket.receive(rcvPacket);
String msg = new String(rcvPacket.getData());
rMsg = msg.trim();
System.out.println(rMsg);
InetAddress rAddr = rcvPacket.getAddress();
temp = rAddr.toString();
System.out.print("Enter message : ");
replyMsg = input.readLine();
if(replyMsg == null)
return ;
addrPacket = new DatagramPacket(temp.getBytes(),temp.getBytes().length, sAddr, sPort);
clientSocket.send(addrPacket);
// System.out.println(temp);
msgPacket = new DatagramPacket(replyMsg.getBytes(),replyMsg.getBytes().length, sAddr, sPort);
clientSocket.send(msgPacket);
// System.out.println(replyMsg);
// System.out.println(sAddr.toString());
}
}catch(IOException ex){System.out.println(ex);}
}
}
Remember that UDP is unreliable.
You should not rely on first packet arriving before (or ever) at the recipient.
You need to provide both the final destination address and the payload in one packet.
My project consists of an application using which users can send files among themselves.
Hence as a basic unit, I developed a FileServer and a FileClient Program.
This code works perfectly fine on localhost but fails on the Network (wifi).
An estimated problem is that the client socket is getting closed or isn't responding after a certain point of time while recieving. But i cant really figure out what the problem is or how to approach the problem.
The error appears is a SocketException: Software caused connection abort. Socket write error.
FileServer CODE:
import java.net.*;
import java.io.*;
public class FileServerPC {
static String remoteIPaddress = "192.168.43.95";
static String filename;
String path;
static File selectedfile = null;
static ServerSocket servsock = null;
static Socket sock = null;
static FileInputStream fis;
static BufferedInputStream bis;
static DatagramSocket theSocket = null;
static DatagramPacket theOutput;
static OutputStream os;
byte[] mybytearray;
static double nosofpackets;
static int packetsize = 1024;
public FileServerPC() {
try {
servsock = new ServerSocket(1500);
theSocket = new DatagramSocket(9999);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
FileServerPC fs = new FileServerPC();
selectedfile = new File("C:\\flower.jpg");
filename = selectedfile.getName();
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
System.out.println("Waiting...");
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
fis = new FileInputStream(selectedfile);
System.out.println((int) selectedfile.length());
long length = selectedfile.length();
System.out.println("LENGTH: " + length);
nosofpackets = Math
.ceil(((int) selectedfile.length()) / packetsize);
// progressBar.setValue(50);
bis = new BufferedInputStream(fis);
String message = length + "`~`" + filename;
byte[] data = message.getBytes();
theOutput = new DatagramPacket(data, data.length,
InetAddress.getByName(remoteIPaddress),8888);
theSocket.send(theOutput);
byte[] newbytearray = new byte[packetsize];
int dur = (int) (selectedfile.length());
int dur1 = dur / 100;
int counter = 0;
System.out.println("duration: " + dur + "nosofpackets: "
+ nosofpackets + "dur1: " + dur1);
int val = 0;
for (int i = 0; i <= nosofpackets ; i++) {
os = sock.getOutputStream();
bis.read(newbytearray, 0, newbytearray.length);
os.write(newbytearray, 0, newbytearray.length);
counter = counter + newbytearray.length;
val = counter / dur1;
System.out.println(val);
os.flush();
}
System.out.println(val);
os.flush();
os.close();
sock.close();
theSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}
}
FileClient CODE:
import java.net.*;
import java.io.*;
public class FileClientPC
{
public static void main(String[] args) throws IOException
{
long start = System.currentTimeMillis();
String remoteip="192.168.43.237";
Socket sock = new Socket(remoteip, 1500);
System.out.println("Connecting...");
InputStream is = sock.getInputStream();
DatagramSocket ds = new DatagramSocket(8888);
byte[] buffer = new byte[65507];
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
try {
ds.receive(dp);
} catch (IOException e) {
System.err.println("chat error2 " + e);
}
String s = new String(dp.getData(), 0, dp.getLength());
String temp[]=s.split("`~`");
String size = temp[0];
String name = temp[1];
System.out.println(size +" "+ name);
long sizeint = Integer.parseInt(size);
System.out.println("Filename: " + name);
FileOutputStream fos = new FileOutputStream("D:\\"+name);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int packetsize = 1024;
double nosofpackets = Math.ceil(sizeint / packetsize);
System.out.println("No of packets: "+Double.toString(nosofpackets));
byte newbytearray[];
for (int i = 0; i <= nosofpackets; i++) {
is = sock.getInputStream();
newbytearray = new byte[packetsize];
int bytesRead = is.read(newbytearray, 0, newbytearray.length);
System.out.println("Packet:" + (i + 1));
bos.write(newbytearray, 0, newbytearray.length);
}
long end = System.currentTimeMillis();
bos.close();
sock.close();
ds.close();
}
}
You need to specify which interface you want to listen to. The default is the local interface. (probably OS dependent). The API for ServerSocket explains how this works (the constructor and bind() functions for instance).
I have a server written in C# and a client side in Android. If I send a message from client (Android) to server (c#) and from server to client, everything works fine. If I try to send one message from client , one from server, another from client, the client remains stuck at reading the message from the server. What could be the problem?
My client code is:
sendBytes("HELLOX".getBytes());
readBytes(byDataReceived);//here it gets stucked
...
try
{
int nrsend=sendBytes("HELLOX".getBytes());
readBytes(byDataReceived);
}
catch (Exception se)
{
Log.d("IdealLog","Exception: "+se.getMessage()+" ");
Toast.makeText(context, se.getMessage()+" " , 10000).show();
// MessageBox.Show(se.Message);
return false;
}
...
public static int readBytes(byte[] myByteArray) throws IOException
{
Log.d("IdealLog","readBytes-begin");
InputStream in = socket.getInputStream();
BufferedReader buffreader = new BufferedReader(new InputStreamReader(in));
String finalText = "";
String text = "";
while ((text = buffreader.readLine()) != null)
{
finalText += text;
}
myByteArray=new byte[myByteArray.length];
myByteArray=EncodingUtils.getAsciiBytes(finalText);
Log.d("IdealLog","Input Stream: "+finalText);
Log.d("IdealLog","TEST: "+EncodingUtils.getAsciiString(myByteArray));
Log.d("IdealLog","readBytes-end");
byDataReceived=myByteArray;
buffreader.close();
return myByteArray.length;//myByteArray.length;
}//readBytes end
public static int sendBytes(byte[] myByteArray) throws IOException
{
return sendBytes(myByteArray, 0, myByteArray.length);
}//sendBytes end
public static int sendBytes(byte[] myByteArray, int start, int len) throws IOException
{
if (len < 0)
{
throw new IllegalArgumentException("Negative length not allowed");
}
if (start < 0 || start >= myByteArray.length)
{
throw new IndexOutOfBoundsException("Out of bounds: " + start);
}
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
// dos.writeInt(len);
if (len > 0)
{
dos.write(myByteArray, start, len);
}
int size=dos.size();
dos.flush();
return size;
}//sendBytes end
My server code:
static void Main(string[] args)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 1408);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ip);
socket.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = socket.Accept();
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);
string welcome = "HELLO&";
byte[] data = new byte[200];
client.Receive(data);
Console.WriteLine("Received data from CLIENT TEST1: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data));
ASCIIEncoding asen = new ASCIIEncoding();
byte[] data2 = new byte[200];
data2 = asen.GetBytes(welcome);
client.Send(data2, data2.Length, SocketFlags.None);
//if i comment out from this 3 lines, everything is working fine
byte[] data3 = new byte[200];//this
client.Receive(data3);//this
Console.WriteLine("Received data from CLIENT TEST2: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data3));//this
Console.WriteLine("Disconnected from {0}", clientep.Address);
client.Close();
socket.Close();
Console.ReadLine();
}
Modify into this:
//if i comment out from this 3 lines, everything is working fine
byte[] data3 = new byte[200];//this
client.Receive(data3);//this
Console.WriteLine("Received data from CLIENT TEST2: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data3));//this
client.Send(data2, data2.Length, SocketFlags.None);
Console.WriteLine("Disconnected from {0}", clientep.Address);
client.Close();
socket.Close();
Console.ReadLine();
}