C# socket and java socket
hello
i am a java programmer,recently we got a project,that need the c# app to communicate with java app ,i select the socket as intermediate.
i notice that java socket term is divided into " blocking" and "non-blocking",the latter come from jdk1.4, the c# socket is devided into "synchronized" and "asynchronized" and both of them are blocking,
in my project,i have tried synchronized c# socket coorperating to blocking java socket,it works well..but when i modify the c# app to ASYNCHRONIZED socket,my system DON'T works well,i don't know why? i can't find asynchronized socket in java,.i learn that nio socket is nonblocking, is it asynchronized?
who can tell me what's is the best solution for the socket communication between java and c#?
yes,i have read them,but it only tell me the communication between java apps,and DON'T tell me any clue about c# socket.
Similar Messages
-
Hello!
I have made my own file sharing program with Java sockets
and i have read a litle bit about raw sockets also.
What are the differences between Java sockets and raw sockets?raw socket can have packet types which Java does not.
Generally if you need something useful which Java cannot do there is a utility already written which does what you want, e.g. ping and you can call that. -
Trusted Solaris and Java sockets
Hello,
Sun has provided a very rich set of Trusted Solaris 8 socket calls.
But how do I use them from Java?
ThanksThanks. I'm a little bit confused. When I use the following code to display the input stream...
byte[] b = new byte[1000];
int ch = is.read(b);
while (ch > -1) {
System.out.print(new String(b, 0, ch));
ch = is.read(b);
}...I see this...
POST / HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Accept-Language: en-gb
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)
Host: localhost
Content-Length: 80
Connection: Keep-Alive
Cache-Control: no-cache
file=C%3A%5Cworkspace%5CConnect%5CTest%5CHTTPTest%5Cres%5Ctest.txt&submit=Upload
...but this doesn't contain the contents of the file that was attached. How can I parse the input stream so I can retrieve the contents of the "temp.txt" file that was attached to the HTML form POST? -
Problems with sockets and InputsStreams
Hi,
I ve this code:
InputStream is = null;
boolean ok=true;
while(ok){
//sc is an object instance of socketConnection
is = sc.openInputStream();
return this.parse(is);
//is.close();
return "";
and this exception is produced:
java.io.IOException: no more Input Streams available.
This exception is produced in the line:
is = sc.openInputStream();
I m connecting to a server and this server sends data throw a socket... but the problem is that when i m reading from this socket and this socket doesn t have data in it...
how could i solve this problem...?
Thanks,
DiegoThat would be the "real" code:
public String process()throws IOException{
InputStream is = null;
is = sc.openInputStream();
String result= this.parse(is);
is.close();
any suggestions?
Thanks,
Diego -
Hi
I would like to developp a client which connects on a java
server.
When i run my program on my developement computer, it works
(maybe because the server and the flex application are on the same
machine.)
But when i want to run the flex application from another
computer I can't manage to get connected...
First question : is it possible to connect flex appli to java
server through internet or network
Example
123.2.2.2:18000 this is the (false) ip on my javaserver (the
port 18000 is open)
and I want to connect to it with a flex application from
another computer.
Thank you for you help
NicolasHi,
I discovered your topic too late so I made a duplicate topic
about socket and java server.
I spend quite a long time trying to solve this problem and I
don't have the solution !
It should be a common question so I guess the answer is so
easy than I can't see it !!
TechNote seams to say that you have to put the
crossdomain.xml file on the root of the (html) server and not on
the server where the flash file is.
The problem is that I don't have or need a web server as my
java server is doing the job. So I don't think it is the answer.
Did you find the answer ?
THX
Jean-Yves -
Problem with socket in java and c++
I am connecting to a server developed in java that use sys/socket.h, this server use DataInputStream
class and readUTF so:
in = new DataInputStream(socket.getInputStream());
inputString = in.readUTF()
My application in C++ it use winsock2.h and I utilize the method "send" in order to send the plots to the server
java got hold of:
#define MAXLONGITUD 10000
char bufEnviados[MAXLONGITUD + 1];
bufEnviados[0] = (0xff & (longitud >> 8));
bufEnviados[1] = (0xff & longitud);
send(sock, bufEnviados,strlen(bufEnviados), 0 );
I send the two first characters with UTF format so that the server in java could recognize them.
The application operated correctly it until received an old plot of 6.236 characters later
from which it close the connection with the socket and it fall my application!
I have carried out several tests and I don't succeed in sending more than those 6.236 characters, however it achievement receibing whatever quantity of characters without problems!
Could somebody help me to resolve this problem? I am attempting of everything and I don't achieve it!
Ahead of time thank you!alfaximena wrote:
#define MAXLONGITUD 10000
char bufEnviados[MAXLONGITUD + 1];
bufEnviados[0] = (0xff & (longitud >> 8));
bufEnviados[1] = (0xff & longitud);
send(sock, bufEnviados,strlen(bufEnviados), 0 );
Are you sending characters or binary data? You mention "plot" which sounds like binary data. You cannot send binary data via character encoding. Characters in java are not just bits, they are mapped values. If you encode it with something like base64 then that should be ok.
I can only suppose that your testing was with data sets greater than 255, because strlen() would not have worked otherwise.
Since you have the size then use it rather than using strlen().
I send the two first characters with UTF format so that the server in java could recognize them.
The application operated correctly it until received an old plot of 6.236 characters later
from which it close the connection with the socket and it fall my application!
There is nothing special about that particular number. So I would guess that the data in that set is the problem. Probably because you are in fact sending binary data. If, for example, a byte with a value of zero showed up in the sequence then strlen() would return an incorrect value compared to the size that you told java you are sending. -
Java 1.3.1 and Detecting Socket Closure (A Popular Question, I Know)
Hi, all. I've been skimming the web looking at various commentary on how it is impossible to detect whether or not a Socket has closed without calling the read of Socket.getInputStream() or the write of Socket.getOutputStream(). I wrote a networking package some months ago that would spawn one Thread for each Socket so I could spare the Threads to block on the I/O, thus following this suggestion. I also understand that Java 1.4 contains various elements of the java.nio package that are supposed to take care of nonblocking I/O. I think, however, that this is entirely possible with Sockets in Java 1.3.1.
I wrote a program that calls Socket.setSoTimeout(), setting the timeout of the socket to 1 millisecond. I then have one Thread looking at a series of open Sockets. The Thread calls the read method on each of the Sockets' InputStream objects and does one of three things based upon the result:
If the result is a successful read, the data is handled as is appropriate.
If the result is a -1, the Socket has been closed and is formally shut down on this side.
If the result is an InterruptedIOException, the Socket is open but has no available data.
The Socket is then ignored until the next pass.
I've tested this idea on an Athalon XP 2100+ and not seen a significant use of processing power.
Therefore, my question is as follows: what's wrong with this idea? We've looked at it and it seems to be an appropriate solution to the problem. Yet, I've seen little mention of this way to work around blocking Socket I/O in Java 1.3.1. It seems appropriate and certainly cuts back on Thread overhead... but does anyone see a catch?
Thanks! Best of luck!This approach to multiplexing seems to not work under the 1.3.1 release for Windows. I have found I still get a -1 on my input stream read, instead of the InterruptedIOException. It's pretty frustrating.
The axact same code appears to work fine on Linux . So this may be dependent on the native code layer for the sockets implementation, or we may be encountering a bug in our or Sun's code. I haven't found documentation of the expected behaviour of the SocketInputStream (the actual class returned by Socket.getInputStream) or the socket implementation in general for each platform.
Note that in general, your approach is not really scalable for the kind of situations the Non-blocking IO package was introduced for. Your approach means that 500 sockets will have a 1/2 second intrinsic delay. You would have to start thread-pooling, etc. You can see why something like an internet audio streaming application would benefit from lower level support in the java libraries.
Neil -
when I use java socket to talk to my proxy, without going through a winsock, my java applet runs fine. However, when I patch winsock in between my java gui and my other proxy, I dont receive anything in the gui. I snoop at packets coming from my other proxy through winsock to my gui and the data is all there. I just cannot receive it.
I use java class DatagramSocket() to establish a socket connection and use class DatagramPacket to get the packets coming. This works if I dont go through a ms proxy.
Can anyone tell me why?How can you snoop at packets comming? I need to know so bad. :-)
Thank you -
Java and VB Socket Communication
Hi All,
I am developing a prototype which need do get some data from Java to VB application. I created server socket in java, My VB application is sending data to the same port what java is running.
The Java program able to recognized some data in coming to the port. but BufferedReader, readLine() not able to read the bytes. Please any one help me to resolve this problem.
Java Code :
public class KnockKnockServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
try{
do{
String headerLine = in.readLine();
if(headerLine==null ||headerLine.equals("\r\n") ||headerLine.equals("") ||headerLine.equals("null")){ System.out.print("");
continue;
}else{
System.out.print(headerLine);
} while(true);
}catch(Exception e){
e.getStackTrace();
out.close();
in.close();
clientSocket.close();
serverSocket.close();
My VB code :
Winsock.Close
If Winsock.State = sckConnected Then
MsgBox "Connected with server"
End If
'Winsock.Protocol = sckTCPProtocol
Winsock.RemoteHost = "insgb0333"
Winsock.RemotePort = 4444
Winsock.Connect
If Winsock.State = sckConnected Then
MsgBox "Connected with server"
End If
Winsock.SendData "test"thx,
My java code not ablt to read the data which sent by my VB code.
String headerLine = in.readLine();
if(headerLine==null ||headerLine.equals("\r\n") ||headerLine.equals("") ||headerLine.equals("null")){
The in.readLine() always returning NULL.
Please help to solve this problem -
Hi all,
I am trying to develop a multi player game using FLEX as the
GUI and pure JAVA
as the server. i want to use a message CLASS between client
and server.
some thing like:
http://www.fireleg.com/
but i want that the communication layer will be a CLASS and
not String.
so I am trying to transfer a CLASS between AS3 and JAVA with
no success.
i am using IExternalizable and Externalizable
(readExternal,writeExternal)
and i am getting: StreamCorruptedException.
I working on it with no success and i wounder if there is a
working example for that.
only 4 classes needed:
AS: client.as , message.as
JAVA: server.java , message.java
P.S
i do not mind using AMF3 as long as i can see a working
example.
thank you
gil michlinHi. Take a look at this blog posting.
http://yaa-blog.blogspot.com/2008/08/remoting-with-blazeds-from-plain.html
Basically, you need to call registerClassAlias yourself rather than having the Flex compiler (mxmlc) do the magic for you.
The mxmlc compiler takes the RemoteClass metadata and creates a registerClassAlias call in a static init block in some actionscript it generates. This actionscript is then compiled into the swf that is your Flex application. If you are not using Flex then you are missing this step and need to write the code that mxmlc would have generated for you.
Hope that helps.
-Alex -
Hi,
I need help ... please ... I have to use socket and not HTTPURLConnection
I try to connect with a socket to a web server (apache2) and request one page but two times.
The first time it works well but the second one it doesn't ... I get a null message.
Why ?
Does the server close the socket as soon as the page is sent ?
If it doesn't how I can continue sending and receiving data on the same socket ?
Here is my code:
package test;
import java.net.*;
import java.io.*;
public class Test
private String laRequete = new String(
"POST http://localhost:5577/Test/ HTTP/1.0\r\n"+
"Host:localhost:5577\r\n"+
"\r\n");
PrintWriter laSortie;
BufferedReader lEntree;
Socket laSocketTCP;
public Test()
String tmp;
try
laSocketTCP = new Socket("localhost", 5577);
laSortie = new PrintWriter(laSocketTCP.getOutputStream());
lEntree = new BufferedReader(new InputStreamReader(laSocketTCP.getInputStream()));
laSortie.println(laRequete);
laSortie.flush();
// Premier essai OK
System.out.println(lEntree.readLine());
while((tmp = lEntree.readLine()) != null)
System.out.println(tmp);
// Second essai => Not OK
laSortie.println(laRequete);
laSortie.flush();
System.out.println(lEntree.readLine());
while((tmp = lEntree.readLine()) != null)
System.out.println(tmp);
catch (Exception e)
e.printStackTrace();
public static void main(String args[])
Test tp = new Test();
Here is the result of the execution
HTTP/1.1 200 OK
Date: Wed, 29 Sep 2004 08:35:35 GMT
Server: Apache/2.0.51 (Win32)
Last-Modified: Wed, 29 Sep 2004 08:27:57 GMT
ETag: "23a46-9a-56c93f9a"
Accept-Ranges: bytes
Content-Length: 154
Connection: close
Content-Type: text/html; charset=ISO-8859-1
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Index Test 1 </TITLE>
</HEAD>
<BODY>
Test 1
</BODY>
</HTML>
null
Thanks, bye.Send an HTTP 1.1 request instead of a 1.0 request.
HTTP 1.0 does not support keeping the connection open, so yes, the server closes the connection.
Dave. -
Problem with Socket and public IP
Hi.
I was create a program to tchat with my friend.
This program turn good in à local network but i obtain
A Connection refused: connect exception when I want
to communiqué by internet :
I write
Socket client = new Socket("my public IP",12347);And I was configurate my router to mapping 12347 port.
Help me please.the exception is :
Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source) -
Conflict between socket and RMI
Hi
I wrote a program in client-server using socket and it was fine. I also wrote a client-server program using RMI. Fine as well. But after I connected the client-server using socket (open socket, send-receive messages, close socket), then use RMI. I got java.rmi.NotBoundException.
Would anyone have a look and provide your feedback please? Thanks.
big J
*****************this is Server.java ***************************
package single;
import java.io.*;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.net.*;
import java.rmi.*;
public class Server
extends Thread {
public static final int SOCKETPORT = 5555;
private String serverName;
public Server() throws IOException {
System.out.println("*** socket opened ***");
serverName = new String("localhost");
ServerSocket serverSocket = new ServerSocket(SOCKETPORT);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
System.out.println(bufferedReader.readLine());
OutputStream os = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(os), true);
printWriter.println("from server");
os.close();
is.close();
socket.close();
System.out.println("*** socket closed ***");
public void runServer() {
System.out.println("*** start of run():RMI ***");
System.setSecurityManager(new SecurityManager());
try {
RMIInterfaceImpl rMIInterfaceImpl = new RMIInterfaceImpl();
Naming.bind("//" + serverName + ":9999/RMIInterface", rMIInterfaceImpl);
catch (RemoteException ex) {
catch (MalformedURLException ex) {
catch (AlreadyBoundException ex) {
System.out.println("*** end of run():RMI ***");
public static void main(String args[]) throws Exception {
Server server = new Server();
server.runServer();
******************this is Client.java **************************
package single;
import java.io.*;
import java.net.*;
import java.rmi.Naming;
public class Client {
private String serverName;
private final static int SOCKETPORT = 5555;
public Client() throws IOException {
serverName = new String("localhost");
Socket socket = new Socket(serverName, SOCKETPORT);
OutputStream os = socket.getOutputStream();
PrintWriter printWriter=new PrintWriter(os, true);
printWriter.println("from client");
InputStream is = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
System.out.println(bufferedReader.readLine());
is.close();
os.close();
socket.close();
public void runClient() throws Exception {
System.out.println("*** start of runClient():RMI ***");
System.setSecurityManager(new SecurityManager());
RMIInterface rMIInterfaceImpl = (RMIInterface) Naming.lookup(
"//" + serverName + ":9999/RMIInterface");
String str = rMIInterfaceImpl.print();
System.out.println(str);
rMIInterfaceImpl.serverSide();
System.out.println("*** end of runClient():RMI ***");
public static void main(String args[]) throws Exception {
Client client = new Client();
client.runClient();
***************** this is RMIInterface.java ***********************
package single;
import java.rmi.Remote;
import java.rmi.RemoteException;
interface RMIInterface
extends Remote {
String print() throws RemoteException;
void serverSide() throws RemoteException;
********************* this is RMIInterfaceImpl.java ***************
package single;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class RMIInterfaceImpl
extends UnicastRemoteObject
implements RMIInterface {
public RMIInterfaceImpl() throws RemoteException {}
public String print() {
return new String("hello world");
public void serverSide(){
System.out.println("this should appear in serverside");I think you have a timing problem between your client and server. As soon as your client and server programs have finished their socket communication, they will both do their "runServer"/"runClient" methods. If the client attempts to lookup the server before the server has registered itself via Naming.bind(), I would expect that's why you're getting a NotBoundException in the client.
You probably wouldn't use the design of your test client/server for something significant, but a quick and dirty way to make this work might be to have the client call Thread.sleep() for a few seconds before trying to do the lookup. -
Problem with the socket and the standard output stream
Hy, I have a little problem with a socket program. It has the server and the client. The problem is that the client at one point in the program, cannot print messages in the console.
My program does the next: the server waits connections, when a client connects to it, the server gets outputstream to the socket and writes two strings on it. Meanwhile, the client gets the inputstream to the socket and reads on it with a loop the two strings written by the server . The strings are printed by the client in the console. The problem starts here; once the read strings are printed ,I mean, after the loop, there are other System.out.println in the client but the console doesnt print anything . It curious that only when I comment on the server code the line that says: "br.readLine()" just before the catch, the client prints all the System.out.println after the loop but why?
Here is the code:
Server code:
public class MyServerSocket {
public MyServerSocket() {
try{
ServerSocket server= new ServerSocket(2000);
System.out.println("servidor iniciado");
Socket client=server.accept();
System.out.println("Client connected");
OutputStream os=client.getOutputStream();
PrintWriter pw= new PrintWriter(os);
String cadena1="cadena1";
String cadena2="cadena2";
pw.println(cadena1);
pw.println(cadena2);
pw.flush();
InputStream is=client.getInputStream();
InputStreamReader isr= new InputStreamReader(is);
BufferedReader br= new BufferedReader(isr);
br.readLine(); //If a comment this line, the client prints after the loop, all the System.out....
catch (IOException e) {
// TODO: handle exception
public static void main(String[] args) {
new MyServerSocket
Client code:
public class MyClientSocket {
public MyClientSocket () {
try{
Socket client= new Socket("localhost",2000);
InputStream is=client.getInputStream();
InputStreamReader isr= new InputStreamReader(is);
BufferedReader br= new BufferedReader(isr);
String read;
while((read=br.readLine())!=null){
System.out.println(read);
//These messages are not printed unless I comment the line I talked about in the server code
System.out.println("leido");
System.out.println("hola");
}catch (IOException e) {
public static void main(String[] args) {
new MyClientSocket
}You are right but with this program the loop ends. As you see, the first class, the Server, writes to the socket one text file. The second class, the client, reads the text file in his socket written by the server and writes it to a file in his machine.
NOTE: The loop in the client ends and the server doesnt make any close() socket or shutdownOutput() .
public class ServidorSocketFicheromio {
public ServidorSocketFicheromio() {
try{
ServerSocket servidor= new ServerSocket(2000);
System.out.println("servidor iniciado");
Socket cliente=servidor.accept();
System.out.println("cliente conectado");
OutputStream os=cliente.getOutputStream();
PrintWriter pw= new PrintWriter(os);
File f = new File("c:\\curso java\\DUDAS.TXT");
FileReader fr= new FileReader(f);
BufferedReader br= new BufferedReader(fr);
String leido;
while((leido=br.readLine())!=null){
pw.println(leido);
pw.flush();
}catch (IOException e) {
* @param args
public static void main(String[] args) {
new ServidorSocketFicheromio();
public class ClienteSocketFicheromio {
public ClienteSocketFicheromio() {
try{
Socket cliente= new Socket("localhost",2000);
File f = new File("G:\\pepe.txt");
FileWriter fw= new FileWriter(f);
PrintWriter pw= new PrintWriter(fw);
InputStream is=cliente.getInputStream();
InputStreamReader isr= new InputStreamReader(is);
BufferedReader br= new BufferedReader(isr);
String leido;
while((leido=br.readLine())!=null){
pw.println(leido);
System.out.println(leido);
System.out.println("leido");
System.out.println("hola");
pw.flush();
}catch (IOException e) {
public static void main(String[] args) {
new ClienteSocketFicheromio();/
} -
Using plain Java Sockets(not RMI) how..?
hi!
1. Using plain Java Sockets(not RMI) how can the client detect when its server
goes down?
There is a long time interval between client requests and the client wants
to retain a live connection rather than disconnect after every reqest.
Please also cc your reply to [email protected]
Thanks,
\RaghuIf you try to send data when the host is gone, it throws an exception. I don'thow to check if it is alive though. I'm having the same problem right now.
Maybe you are looking for
-
Hi, I'm writing an HTMLDB application that we will be using to track the number of hours that we put into a project (all projects), and I've got a routine that returns the number of hours that are possible within a given month M-F 8 hours a day. I us
-
MSExchangeMonitoring service does not start
Hi, I have installed the exchange management pack on a SCOM 2012 R2 monitoring server and am trying to monitor a exchange 2010 server. The MSExchangeMonitoring service does not want to start, it just keeps trying but always has the status of "startin
-
Seeking advice on Best Practices for XML Storage Options - XMLTYPE
Sparc64 11.2.0.2 During OOW12 I tried to attend every xml session I could. There was one where a Mr. Drake was explaining something about not using clob as an attribute to storing the xml and that "it will break your application." We're moving forwar
-
CUPC supported on 64-bit version of Windows 7?
Hi there, anybody knows when we can expect CUPC to be supported on 64-bit version of Windows 7 platform? Regards, Tenaro
-
V2 Flash components unsupported in Director?
Page 11 of http://www.adobe.com/support/director/flash_8_asset_xtra.pdf states that v2 Flash components are unsupported by the Flash Asset Xtra. What exactly does this mean, particularly when all the built-in Flash components are v2 components, aren'