服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java socket 通讯的代码例子


实现client端功能的clientapp.java原文件:

import java.net.*;
import java.io.*;
import java.lang.*;

public class clientapp
{
public static void main(string args[])
{
try
{
//创建通讯并且和主机rock连接
socket csocket=new socket("192.168.100.188",8018);
//打开这个socket的输入/输出流
outputstream os=csocket.getoutputstream();
datainputstream is=new datainputstream(csocket.getinputstream());

int c;
boolean flag=true;

string responseline;

while(flag)
{
//从标准输入输出接受字符并且写如系统
while((c=system.in.read())!=-1)
{
os.write((byte)c);
if(c=='/n')
{
os.flush();
//将程序阻塞,直到回答信息被收到后将他们在标准输出上显示出来
responseline=is.readline();
system.out.println("message is:"+responseline);
}
}
}
os.close();
is.close();
csocket.close();

}
catch(exception e)
{
system.out.println("exception :"+ e.getmessage());
}
}
}


实现server端功能的serverapp.java原文件:

import java.net.*;
import java.io.*;

public class serverapp
{
public static void main(string args[])
{
try
{
boolean flag=true;
socket clientsocket=null;
string inputline;
int c;

serversocket ssocket=new serversocket(8018);
system.out.println("server listen on:"+ssocket.getlocalport());

while(flag)
{
clientsocket=ssocket.accept();
datainputstream is= new datainputstream(new bufferedinputstream(clientsocket.getinputstream()));
outputstream os=clientsocket.getoutputstream();

while((inputline=is.readline())!=null)
{
//当客户端输入stop的时候服务器程序运行终止!
if(inputline.equals("stop"))
{
flag=false;
break;
}
else
{
system.out.println(inputline);

while((c=system.in.read())!=-1)
{
os.write((byte)c);
if(c=='/n')
{
os.flush(); //将信息发送到客户端
break;
}
}
}


}
is.close();
os.close();
clientsocket.close();

}
ssocket.close();
}
catch(exception e)
{
system.out.println("exception :"+ e.getmessage());
}
}
}

扫描关注微信公众号