`
txf2004
  • 浏览: 6866541 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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

 
阅读更多
// 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();
}

}


}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics