Java プログラムがソケット プログラミングを使用して TCL プログラムと通信するシナリオのプログラムを作成する必要があります。TCL と Java のソケット プログラミングを個別に試してみました。しかし、Java プログラムをクライアント ソケットとして使用し、TCL プログラムをサーバーとして使用する必要があるため、うまく実行できません。
サーバー用TCLプログラム
set svcPort 9999
#Implement the service
# This example just writes the info back to the client...
proc doService {sock msg} {
puts $sock "$msg"
}
# Handles the input from the client and client shutdown
proc svcHandler {sock} {
set l [gets $sock] ;# get the client packet
puts "The packet from the client is $l"
if {[eof $sock]} { ;# client gone or finished
close $sock ;# release the servers client channel
} else {
doService $sock $l
}
}
# Accept-Connection handler for Server.
# called When client makes a connection to the server
# Its passed the channel we're to communicate with the client on,
# The address of the client and the port we're using
#
# Setup a handler for (incoming) communication on
# the client channel - send connection Reply and log connection
proc accept {sock addr port} {
# if {[badConnect $addr]} {
# close $sock
# return
# }
# Setup handler for future communication on client socket
fileevent $sock readable [list svcHandler $sock]
# Read client input in lines, disable blocking I/O
fconfigure $sock -buffering line -blocking 0
# Send Acceptance string to client
puts $sock "$addr:$port, You are connected to the echo server."
puts $sock "It is now [exec date]"
# log the connection
puts "Accepted connection from $addr at [exec date]"
}
# Create a server socket on port $svcPort.
# Call proc accept when a client attempts a connection.
socket -server accept $svcPort
vwait events ;# handle events till variable events is set
と
Java クライアント プログラム
// File Name GreetingClient.java
import java.net.*;
import java.io.*;
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName
+ " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress()+"\n");
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
サーバーを起動しましたが、サーバーには何も表示されません。
クライアントを起動すると、サーバーは「2013 年 5 月 6 日月曜日 02:50:21 PDT 2013 からの接続を受け入れました」と表示し、クライアントは「ポート 9999 に接続中 /(サーバーの IP アドレス):9999 に接続しました」と表示します
out.writeUTF がクライアントで実行されると、サーバーは「クライアントからのパケットは
"Hello from : /<client ip address>:<client port no>".
、サーバーからの応答を表示することになっているため、クライアントには何も表示されません。クライアント プロセスは終了せず、の実行を待ちますSystem.out.println("Server says " + in.readUTF());
。
誰かがここで助けて、接続があるのにクライアントがサーバーからの応答を見ることができず、クライアントがサーバーにデータを送信できる理由を教えてください。
ありがとう