Posted to tcl by Cactapus at Sat Nov 17 18:04:06 GMT 2012view raw

  1. # Read data from a channel (the server socket) and put it to stdout
  2. proc read_sock {sock} {
  3. set l [gets $sock]
  4. puts stdout "ServerReply:$l"
  5. flush $sock
  6. }
  7.  
  8. # open the connection to the echo server...
  9. set shost "localhost"
  10. set sport 5555
  11.  
  12. # set up connection:
  13. set svrSock [socket $shost $sport]
  14.  
  15. #if {[eof $svrSock]} { # connection closed}
  16.  
  17. # Setup monitoring on the socket so that when there is data to be
  18. # read the proc "read_sock" is called
  19. fileevent $svrSock readable [list read_sock $svrSock]
  20.  
  21. # configure channel modes
  22. # ensure the socket is line buffered so we can get a line of text
  23. fconfigure $svrSock -buffering line
  24.  
  25. # message indicating connection accepted and we're ready to go
  26. puts "Connected to server"
  27.  
  28. # wait for and handle either socket or stdin events...
  29. vwait eventLoop
  30.  
  31. puts "Client Finished"
  32.  
  33.  
  34.  
  35.  
  36.  
  37. ############### Java
  38. import java.io.*;
  39. import java.net.*;
  40. public class EchoClient{
  41. ServerSocket providerSocket;
  42. Socket connection = null;
  43. ObjectOutputStream out;
  44. ObjectInputStream in;
  45. String message;
  46.  
  47. void connect(){
  48. try {
  49. //1. creating a server socket
  50. providerSocket = new ServerSocket(5555, 10);
  51. //2. Wait for connection
  52. System.out.println("Waiting for connection");
  53. connection = providerSocket.accept();
  54. System.out.println("Connection received from " + connection.getInetAddress().getHostName());
  55. //3. get Input and Output streams
  56. out = new ObjectOutputStream(connection.getOutputStream());
  57. //in = new ObjectInputStream(connection.getInputStream());
  58.  
  59. out.flush();
  60.  
  61. } catch (IOException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65.  
  66. void run(){
  67. // test message
  68. sendMessage(1 + ";" + 0 + ";" + 0 + ";" + 10 + ";");
  69. }
  70.  
  71. void sendMessage(String msg)
  72. {
  73. try{
  74. out.writeChars(msg);
  75. out.flush();
  76.  
  77. System.out.println("server> " + msg);
  78. //out.
  79. }
  80. catch(IOException ioException){
  81. ioException.printStackTrace();
  82. }
  83. catch(IllegalMonitorStateException e){
  84. e.printStackTrace();
  85. }
  86. }
  87. public static void main(String args[])
  88. {
  89.  
  90. EchoClient server = new EchoClient();
  91. server.connect();
  92. while(true){
  93. server.run();
  94. }
  95. }
  96. }