我需要写一个程序,实现Java程序通过Socket编程与TCL程序进行通信。我已经成功地分别尝试了TCL和Java的Socket编程。但是,由于我需要将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();
}
}
}
我启动了服务器,但服务器没有显示任何东西。
我启动了客户端,服务器显示“接受来自于(client ip address)的连接,时间为2013年5月6日星期一02:50:21 PDT”,客户端显示“正在连接到(server ip address) 的9999端口,已连接上/(server ip address):9999”。
当在客户端执行out.writeUTF时,服务器会显示“来自客户端的数据包是“Hello from: /<client IP地址>:<client 端口号>”。但是客户端并没有像应该显示服务器的回复那样显示任何内容。客户端进程没有退出,而是等待执行“System.out.println("Server says " + in.readUTF());”。
请问有人可以帮忙解决问题并告诉为什么客户端连接后无法看到服务器的回复,但却能向服务器发送数据吗?
谢谢!
writeUTF
并没有发送你所期望的内容... - Donal Fellows