I try to send a string consist of some lines in one datagram packet from my client to server ,my problem is when I send the string only first line will send to the server ,I want to send one line then after 10 second send another line and another, how can I solve it???
this is my client code for sending string :
String msge="null";
String atCurrentLine = null;
try (BufferedReader cl = new BufferedReader(
new FileReader("Client1.txt"))) {
while ((atCurrentLine = cl.readLine()) != null) {
msge=atCurrentLine;
System.out.println(msge);
}
} catch (IOException e) {
e.printStackTrace();
}
DatagramSocket skt = null;
try {
skt = new DatagramSocket();
byte[] b = msge.getBytes();
InetAddress host = InetAddress.getByName("localhost");
int cl = 6700;
DatagramPacket request = new DatagramPacket(b,b.length,host,cl);
skt.send(request);
and this code for server to receive:
DatagramSocket skt = null;
try {
skt = new DatagramSocket(6700);
byte [] buffer = new byte[1000];
while (true) {
DatagramPacket request = new DatagramPacket(buffer,buffer.length);
skt.receive(request);
String [] arrayMsg = (new String(request.getData())).split(" ");
sms=arrayMsg[0];
System.out.println("received from client :"+arrayMsg[0]);
Related
I am trying to set up Client-Server communication where C# is the
server side and Java is the client side. The connection is successful
and I am able to send a string from C# to Java. However, I am having
issues sending a string from Java to C#. The Server does not get any
input.
My code is the following: Server Side C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace ServerToJava
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(5678);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
requestCount = 0;
NetworkStream networkStream = clientSocket.GetStream();
try
{
requestCount = requestCount + 1;
string serverResponse = "Last Message from client server This is a test";
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
Console.Write ("ReadClient Thread started");
int length = networkStream.ReadByte ();
byte[] buffer = new byte[length];
int size = networkStream.ReadByte ();
byte[] buff = new byte[size];
using (var memoryStream = new MemoryStream(buff,false)) {
using (var streamReader = new StreamReader(memoryStream, Encoding.UTF8)) {
var message = streamReader.ReadLine();
buff = Encoding.UTF8.GetBytes(message);
networkStream.Read(buffer, 0 ,buffer.Length);
Console.Write (message);
networkStream.Flush();
}
}
}
catch (Exception ex)
{
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
}
}
}
Client Side Java
OutputStream out;
Socket s = new Socket("127.0.0.1", 5678);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
out= s.getOutputStream();
out.write('a');
System.exit(0);
You shouldn't use new TcpListener(5678) it is Obsolete, instead use the following:
// Set the TcpListener on port 5678.
Int32 port = 5678;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener server = new TcpListener(localAddr, port);
Source` MSDN
I am trying to send set of files through socket C# and Java application, I am not able to recieve all files. The server application closes connections, I think, because the server always closes connection after sending the file without making sure that the client app received the file.
Here is the C# client code:
public static void connectWithRemoteServer(string strIp, string strMessage, out
string strResult)
{
strResult = "";
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(strIp, 1593);
NetworkStream networkStream = tcpClient.GetStream();
StreamReader sr = new StreamReader(networkStream);
if (strMessage.Substring(0,1).Equals("s"))
{
byte[] byteBuffer = Encoding.ASCII.GetBytes(strMessage);
networkStream.Write(byteBuffer, 0, byteBuffer.Length);
strResult = sr.ReadLine();
}
else if (strMessage.Substring(0, 1).Equals("f"))
{
byte[] byteBuffer = Encoding.ASCII.GetBytes(strMessage);
networkStream.Write(byteBuffer, 0, byteBuffer.Length);
int length = int.Parse(sr.ReadLine());
byte[] buffer = new byte[length];
networkStream.Read(buffer, 0, (int)length);
string var = strMessage.Substring(1);
//write to file
BinaryWriter bWrite = new BinaryWriter(File.Open(var, FileMode.Create));
bWrite.Write(buffer);
bWrite.Flush();
bWrite.Close();
strResult = "ok";
}
tcpClient.Close();
}
}
foreach (string strFilePath in lst)
{
Utilities.connectWithRemoteServer("192.168.0.167", "f" + strFilePath, out str);
}
Java Server app
while(true)
{
String listeFiles = "";
ServerSocket serverSocket = new ServerSocket(1593);
System.out.println("Server started and waiting for request..");
Socket socket = serverSocket.accept();
System.out.println("Connection accepted from " + socket);
// this is to send to the client application
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// this is to receive from the client application
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
byte[] bytearray = new byte[in.available()];// recived byte from the
// client application
in.read(bytearray, 0, bytearray.length);// read recieved byte from
String strRecieved = new String(bytearray);// get the received string
System.out.println(strRecieved);
//strRecieved = strRecieved.trim();
if(strRecieved.substring(0,1).equals("s"))
{
List<String> lstFiles = GetFiles.getListFilesPath("./testData");
for (String str : lstFiles) {
listeFiles = str + "+" + listeFiles;
}
String listFilesToSend = listeFiles.substring(0, listeFiles.length() - 1);
out.println(listFilesToSend);
System.out.println("List Files Send ");
serverSocket.close();
socket.close();
}
else if (strRecieved.substring(0,1).equals("f"))
{
File file = new File(strRecieved.substring(1));
// // send file length
out.println(file.length());
// read file to buffer
byte[] buffer = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.read(buffer, 0, buffer.length);
// // send file
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(buffer);
bos.flush();
serverSocket.close();
socket.close();
}
}
}
How to make sure the file has been received successfully before send the next file Issue
unable to write data to the transport connection an existing connection was forcibly closed
Any help would be appreciated.
Thank you .
I'm connecting to a remote TCP Listener that receives a string, and responds with a response.
Going from my Windows 8 Phone App, to a Java Jar. The Jar IS receiving the message, but the Windows 8 Phone App is not getting the response.
C# Code
outputClient.Connect (/IP ADDRESS/, /Port/);
using (Socket sock = outputClient.Client) {
sock.Send (UTF8Encoding.ASCII.GetBytes (broadcastMessage));
var response = new byte[100];
sock.Receive (response);
var str = Encoding.ASCII.GetString (response).Replace ("\0", "");
Console.WriteLine ("[RECV] {0}", str);
} <-- JAVA CODE DOESN'T GET HIT UNTIL THIS LINE IS COMPLETED
Java Code
String clientSentence;
ServerSocket socketServer = new ServerSocket(/* PORT */);
while (true)
{
Socket connectionSocket = socketServer.accept();
connectionSocket.setKeepAlive(true);
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
clientSentence = inFromClient.readLine();
BufferedWriter outToClient = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
if (clientSentence != null)
{
try
{
JsonObject json = new JsonParser().parse(clientSentence).getAsJsonObject();
String un = json.get("Username").toString();
String uuid = "2c9c79a096ef4d869fb1d1e07469bb41".replaceAll(
"(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})",
"$1-$2-$3-$4-$5");
var val = /* Get val */
String response = gson.toJson(val);
outToClient.write(response);
outToClient.newLine();
outToClient.flush();
}
catch (Exception ex)
{
ex.printStackTrace();
outToClient.write(response);
outToClient.newLine();
outToClient.flush();
}
}
connectionSocket.close();
}
A little more explanation: JAVA CODE DOESN'T GET HIT UNTIL THIS LINE IS COMPLETED means that the socket appears to not be sending until using (Socket sock = outputClient.Client) is no longer being used.
I fixed it by replacing the C# code with:
using (TcpClient client = new TcpClient (/IP ADDRESS/, /PORT/))
using (NetworkStream stream = client.GetStream ())
using (StreamReader reader = new StreamReader (stream))
using (StreamWriter writer = new StreamWriter (stream)) {
writer.AutoFlush = true;
foreach (string lineToSend in linesToSend) {
Console.WriteLine ("Sending to server: {0}", lineToSend);
writer.WriteLine (lineToSend);
string lineWeRead = reader.ReadLine ();
Console.WriteLine ("Received from server: {0}", lineWeRead);
Thread.Sleep (2000); // just for effect
}
Console.WriteLine ("Client is disconnecting from server");
}
I am trying to send a "request line" and a file through a socket.
Client (sender)
Socket socket = new Socket(hostName, SOCKET_PORT);
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
FileInputStream fis = new FileInputStream(fileName);
os.writeBytes("PUT c:\dev\foo\helloworld.txt" + "\r\n")
byte[] buffer = new byte[1024];
int bytes;
while((bytes = fis.read(buffer)) != -1 ) {
try {
os.write(buffer, 0, bytes);
} catch (IOException e) {e.printStackTrace();}
}
Sever (receiver)
ServerSocket serverSocket = new ServerSocket(SOCKET_PORT);
Socket clientSoc = serverSocket.accept();
InputStream inputStream = clientSoc.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String requestLine = bufferedReader.readLine();
File currentFile = (File)new ObjectInputStream(inputStream).readObject(); //This doesn't work
byteSequence = new byte[new Long(currentFile.length()).intValue()];
for(int i =0; i<currentFile.length();i++){
byteSequence[i] = (byte)clientSoc.getInputStream().read();
}
try {
FileOutputStream newFile = new FileOutputStream(currentFile.getName());
newFile.write(byteSequence,0, byteSequence.length);
} catch (IOException e) {e.printStackTrace();}
I am able to read the request line on the server but when I attempt to read the file it throws an exception (line below).
File currentFile = (File)new ObjectInputStream(inputStream).readObject();
java.io.Stream.CorruptedException:
java.io.StreamCorruptedException: invalid stream header: 0A48656C
What exactly am I doing wrong?
You are trying to access an object that was not even passed to the socket.. you only passed a byte of string to the server but you never pass an Object to the server using the ObjectOutputStream..
i have this assignment where i am supposed to write a proxy server that uses java sockets to handle get requests from a client. I am now stuck and have been looking all over google to find the answer but without success.
Christoffers solution helped my with my first problem. Now that i have updated the code this is what i am using.
The problem is that it only downloads parts of most webpages before it gets stuck on sending the packets back to the client loop. At the moment I cant explain why it is behaving the way it is.
public class MyProxyServer {
//Set the portnumber to open socket on
public static final int portNumber = 5555;
public static void main(String[] args){
//create and start the proxy
MyProxyServer myProxyServer = new MyProxyServer();
myProxyServer.start();
}
public void start(){
System.out.println("Starting MyProxyServer ...");
try {
//create the socket
ServerSocket serverSocket = new ServerSocket(MyProxyServer.portNumber);
while(true)
{
//wait for a client to connect
Socket clientSocket = serverSocket.accept();
//create a reader to read the instream
BufferedReader inreader = new BufferedReader( new InputStreamReader(clientSocket.getInputStream(), "ISO-8859-1"));
//string builder for preformance when we loop over the inputstream and read lines
StringBuilder builder = new StringBuilder();
String host = "";
for (String buffer; (buffer = inreader.readLine()) != null;) {
if (buffer.isEmpty()) break;
builder.append(buffer.replaceAll("keep-alive", "close"));
if(buffer.contains("Host"))
{
//parse the host
host = buffer.replaceAll("Host: ", "");
}
System.out.println(buffer);
}
String req = builder.toString();
System.out.println("finshed reading \n" + req);
System.out.println("host: " + host);
//new socket to send the information over
Socket s = new Socket(InetAddress.getByName(host), 80);
//printwriter to send text over the output stream
PrintWriter pw = new PrintWriter(s.getOutputStream());
//send the request from the client
pw.println(req+"\r\n");
pw.flush();
//create inputstream to receive the web page from the host
BufferedInputStream in = new BufferedInputStream(s.getInputStream());
//create outputstream to send the web page to the client
BufferedOutputStream outbuffer = new BufferedOutputStream(clientSocket.getOutputStream());
byte[] bytebuffer = new byte[1024];
int bytesread;
//send the response back to the client
while((bytesread = in.read(bytebuffer)) != -1) {
System.out.println(bytesread);
outbuffer.write(bytebuffer,0, bytesread);
outbuffer.flush();
}
System.out.println("done sending");
//close the streams
inreader.close();
s.close();
pw.close();
outbuffer.close();
in.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch(RuntimeException e){
e.printStackTrace();
}
}
}
If anyone could explain to me why i cant get it working correctly and how to solve it I would be very grateful!
Thanks in advance.