Java 通过 socket 实现 服务器和客户端的通信 TCP

作者: admin 分类: 学习文档 发布时间: 2011-11-03 23:03
 // JBulder 9.0下执行package me;
import java.net.* ; //网络编程有关的类在此包
import java.io.* ; //用到 输入输出流
public class JavaNet
{
public static void main(String []args)
{

if(args.length>0)
runServer() ;
else
runClient() ;

 

}

static public void runServer() //服务端
{
try
{
ServerSocket s1 = new ServerSocket(6666);
while(true)
{
Socket ss=s1.accept() ; //等待连接的到来
InputStream in= ss.getInputStream() ; //获得输入流
OutputStream out=ss.getOutputStream() ; //获得输出流
out.write(“hellow welcome”.getBytes()) ; //向输出流写入数据
byte ch[] =new byte[100];
int num=in.read(ch) ;
System.out.println(new String(ch,0,num));
in.close();
out.close();
ss.close();
}
}catch(Exception e)
{
e.printStackTrace();
}
}
static public void runClient() //客户端
{
try{
Socket ss=new Socket(InetAddress.getByName(“127.0.0.1″),6666) ; //getByname null返回本地IP “LocalHost” 返回本地 IP也返回本地
OutputStream out=ss.getOutputStream() ; //获得输出流 向服务器写入数据
out.write(“I am zhangsan “.getBytes());
}
catch (Exception e)
{
e.printStackTrace();
}

 

 

}

 

 

 
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!

发表评论

电子邮件地址不会被公开。

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Protected by WP Anti Spam