下面是一个客户端的Socket程序【基于java编程技术】
环境:OS : Windows XP Tools: Eclipse 3.4.1
import java.io.*;
import java.net.*;
public class test {
public static void main(String[] args)
{
try{
Socket clientSocket = new Socket("192.168.8.2",9800);
OutputStream output=clientSocket.getOutputStream();
DataInputStream input= new DataInputStream(clientSocket.getInputStream());
int c;
String response;
while((c=System.in.read())!=-1)
{
output.write((byte)c);
if(c=='\n'){
output.flush();
response=input.readLine();
System.out.println("Communication:"+response);
}
}
output.close();
input.close();
clientSocket.close();
} catch(Exception e) {
System.err.println("Exception:"+e);
}
}
}
这个程序是一个非常的简单的数据通讯的例子,程序先创建了一个Socket并和主机192.168.8.2上的端口9800相连接,然后打开输入输出流,接着程序从标准输入接收字符并写入流中,每写满一行(以用户键入回车为标志),就把缓冲区中的字符串送往mice上的服务器端程序进行处理,等待服务器端的应答。input.readLine()方法调用将导致程序停滞直到收到应答信息,程序将一直重复这个过程,直到用户输入中止符。最后程序要关闭socket输入输出流,在关闭socket和服务器端的连接。