【 as程序部分 】
//建立XMLSocket对象
var mySocket = new XMLSocket();
mySocket.connect("127.0.0.1",3000);
//========== 测试建立socket连接是否成功 ==========================
mySocket.onConnect = function(success)
{
if(success)
{
_root.ifconnectok = "ok";
trace("connect ok");
}
else
{
_root.ifconnectok = "failed";
trace("connect failed");
}
}
//====== End for 测试是否连接成功 =============================
//成功建立连接后 向服务器端发送一个测试用的字符串,以便服务器端能显示出信息。
mySocket.send("this is a testing String !!!");
【 java程序部分 】
import java.io.*;
import java.net.*;
public class LocalServer
{
protected int listenPort = 3000;
public void acceptConnections()
{
try
{
ServerSocket server = new ServerSocket(this.listenPort);//同客户机的Socket对应,在服务器端,我们需要ServerSocket对象,参数是兼听的端口号
Socket incomingConnection = null;//创建一个客户端的Socket变量,以接收从客户端监听到的Socket
handleConnection处理
System.out.println("Server端正在等待一个socket连接......");
incomingConnection = server.accept();//调用该 ServerSocket 的 accept() 来告诉它开始侦听
System.out.println("一个socket客户端已经连接过来......");
handleConnection(incomingConnection);
} catch (BindException e) {
System.out.println("Unable to bind to port " + listenPort);
} catch (IOException e) {
System.out.println("Unable to instantiate a ServerSocket on port: " + listenPort);
}
}
public void handleConnection(Socket incomingConnection)
{
System.out.println("\r正在对此连接进行处理......");
try
{
//首先获取同Socket相关联的流outputToSocket和InputStream
//其中outputToSocket是要返回给客户端Socket的流
//InputStream是客户端发来的请求,在这里就是文件路径,即"RemoteFile.txt"
OutputStream outputToSocket = incomingConnection.getOutputStream();
InputStream inputFromSocket = incomingConnection.getInputStream();
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputFromSocket)); //首先要将InputStream转换到BufferedReader中
String line = null;
while ((line = streamReader.readLine()) != null)
{
System.out.println(line); //从streamReader中读出文件信息,直接输出到默认输出设备中(本例中是指dos窗口)
}
System.out.println("\r\r接受信息完毕!");
//完成之后关闭所有流,注意关闭Socket流的顺序
streamReader.close();
} catch (Exception e) {
System.out.println("Error handling a client: " + e);
}
}
//主程序,建立sever实例对象,然后运行对象的acceptConnections()方法
public static void main(String[] args) {
LocalServer server = new LocalServer();
server.acceptConnections();
}
}
文章评论(0条评论)
登录后参与讨论