用户名 密码 [R] 注册 [F] 忘记密码
设为首页 加入收藏

Java socket 入门编程实例

[ 字号: ] [ 关闭 ] 2008-4-27 20:21:04 互联网 作者:黄相如整理 浏览次数: 发表评论

关键词:Java socket 入门编程实例

这是一个C/S之间通信的例子,在JDK1.4下测试通过.
//服务器端源程序tcpserver.java

import java.io.*;
import java.net.*;
public class tcpserver
{
public static void main(String[] args) throws IOException
{
ServerSocket svrsoc=null;
Socket soc=null;
DataInputStream in=null;
PrintStream out=null;
InetAddress clientIP=null;
String str=null;
try
{
svrsoc=new ServerSocket(8000);
System.out.println("Server start....");
soc=svrsoc.accept();

in=new DataInputStream(soc.getInputStream());
out=new PrintStream(soc.getOutputStream());
clientIP=soc.getInetAddress();
System.out.println("Client''s IP address:"+clientIP);
out.println("welcome.....");
str=in.readLine();
while (!str.equals("quit"))
{
System.out.println("Client said:"+str);
str=in.readLine();
}
System.out.println("Client want to leave");
}
catch(Exception e)
{
System.out.println("error:"+e);
}
finally
{
in.close();
out.close();
soc.close();
svrsoc.close();
System.exit(0);
}
}
}

//客户端源程序tcpclient.java

import java.io.*;
import java.net.*;
public class tcpclient
{
public static void main(String[] args) throws IOException
{
Socket soc=null;
DataInputStream in=null;
PrintStream out=null;
DataInputStream sysin=null;
String strin=null;
String strout=null;
try
{
soc=new Socket(args[0],8000);
System.out.println("Connecting to the Server");
in=new DataInputStream(soc.getInputStream());
out=new PrintStream(soc.getOutputStream());
strin=in.readLine();
System.out.println("Server said:"+strin);
sysin=new DataInputStream(System.in);
strout=sysin.readLine();
while (!strout.equals("quit"))
{
out.println(strout);
strout=sysin.readLine();
}
out.println(strout);
}
catch(Exception e)
{
System.out.println("error:"+e);
}
finally
{
in.close();
out.close();
soc.close();
sysin.close();
System.exit(0);
}
}
}



上一页:网站LOGO的设计与作用
下一页:合格站长必须知道的建站常识

评论

发表评论
[ 字号大小: ] [ 加入收藏 ] [ 打印 ] [ 关闭 ]

传播互联网精神,研究互联网学术,分享互联网经验,普及互联网应用,追求互联网梦想,共创电子商务辉煌!
Copyright 2008 RoyEC.com罗伊 All Rights Reserved.
沪ICP备07510814号 |