java连接socket
java编程对于Socket之间的通信过程如下:
服务端往Socket的输出流里面写东西,客户端就可以通过Socket的输入流读取对应的内容。Socket与Socket之间是双向连通的,所以客户端也可以往对应的Socket输出流里面写东西,然后服务端对应的Socket的输入流就可以读出对应的内容。下面来看一些服务端与客户端通信的例子:
publicclassServer{
publicstaticvoidmain(Stringargs[])throwsIOException{
//为了简单起见,所有的异常信息都往外抛
intport=8899;
//定义一个ServerSocket监听在端口8899上
ServerSocketserver=newServerSocket(port);
//server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的
Socketsocket=server.accept();
//跟客户端建立好连接之后,我们就可以获取socket的InputStream,并从中读取客户端发过来的信息了。
Readerreader=newInputStreamReader(socket.getInputStream());
charchars[]=newchar[64];
intlen;
StringBuildersb=newStringBuilder();
while((len=reader.read(chars))!=-1){
sb.append(newString(chars,0,len));
}
System.out.println("fromclient:"+sb);
reader.close();
socket.close();
server.close();
}
}
客户端代码
Java代码publicclassClient{
publicstaticvoidmain(Stringargs[])throwsException{
//为了简单起见,所有的异常都直接往外抛
Stringhost="127.0.0.1";//要连接的服务端IP地址
intport=8899;//要连接的服务端对应的监听端口
//与服务端建立连接
Socketclient=newSocket(host,port);
//建立连接后就可以往服务端写数据了
Writerwriter=newOutputStreamWriter(client.getOutputStream());
writer.write("HelloServer.");
writer.flush();//写完后要记得flush
writer.close();
client.close();
}
}
❷ 如何干净的实现Android/Java Socket 长连接通信
JavaSocket通信有很多的时候需要我们不断的学习。方面效率虽然不及C与C++但它以灵活语言优势,为大家广为使用。本文就对在使用java做通信方面程序时候应改注意问题做以说明。
1.长连接、短链接只是针对客户端而言,服务器无所谓长、短;
2.无论同步或者异步通信,发送之后务必要又响应回复,确认收到,负责进行一定范围内重发,例如重发三次;
3.长连接服务器与客户端之间务必需要心跳探测,由客户端主动发起;
4.短连接服务器通用代码:
python">packagecom.biesan.sms.gate.unioncom.communication;
importcom.biesan.commons.Constants;
importcom.biesan.commons.util.CodeUtil;
importcom.biesan.sms.gate.unioncom.data.*;
importcom.biesan.sms.gate.unioncom.util.GateInfo;
importjava.net.*;
importjava.io.*;
importjava.util.*;
importorg.apache.log4j.*;
importspApi.*;
{
//stopflag
privatebooleanunInterrupt=true;
privatebooleanunErr=true;
//privatebooleancloseSocketFlag=false;
//serversocket
privateServerSocketserverSo=null;
//currentsocket
privateSocketso=null
privateOutputStreamoutput=null;
privateInputStreaminput=null;
//gatecommand
privateSGIP_CommandtmpCmd=null;
privateSGIP_Commandcmd=null;
privateBindbind=null;
privateBindRespbindResp=null;
//privateUnbinnBind=null;
privateUnbindRespunBindResp=null;
=true;
LoggerunioncomLog=Logger.getLogger(Unioncom
Deliver.class.getName());
publicUnioncomDeliver(){
}
publicvoidrun(){
unioncomLog.info("Start...");
while(unInterrupt){
this.initServer();
this.startServices();
while(this.unAcceptErrorFlag){
try{
//接受连接请求
unioncomLog.info("beforeacceptconnection!.......
FreeMemroy:"+Runtime.getRuntime().freeMemory());
this.acceptConnection();
unioncomLog.info("afteracceptconnection!.......
FreeMemroy:"+Runtime.getRuntime().freeMemory());
while(unErr){
cmd=newCommand();
unioncomLog.info("beforereadcommandfromstream
...........FreeMemroy:"+Runtime.getRuntime().
freeMemory());
tmpCmd=cmd.read(input);
unioncomLog.info("afterreadcommandfromstream"+
getCommandString(cmd.getCommandID())+"FreeMemroy:"+
Runtime.getRuntime().freeMemory());
if(tmpCmd==null){
unErr=false;
break;
}
switch(cmd.getCommandID()){
//biadreadycommunication
caseSGIP_Command.ID_SGIP_BIND:{
this.dealBind();
break;
}//exitbind
caseSGIP_Command.ID_SGIP_UNBIND:{
this.dealUnBind();
unioncomLog.info("afterunbindconnection!.......
FreeMemroy:"+Runtime.getRuntime().freeMemory());
break;
}//deliver
....
default://错误的命令字
break;
}//switch
}//while(unErr)
}catch(Exceptione){
unioncomLog.error("UnioncomRecvServiceError"
+e.getMessage());
}finally{
if(this.so!=null){
this.closeSocket();
}
this.unErr=true;
}
}//while(this.unAcceptErrorFlag)
try{
this.closeServerSocket();
sleep(200);//sleep
}catch(InterruptedExceptionie){
}
}//while(unInterrupt)
}
privateStringgetCommandString(intcmd){
switch(cmd){
//biadreadycommunication
caseSGIP_Command.ID_SGIP_BIND:{
return"BINDCOMMAND";
}//exitbind
caseSGIP_Command.ID_SGIP_UNBIND:{
return"UNBINDCOMMAND";
}//deliver
case...
default:
return"UNKNOWNCOMMAND";
}
}
privatevoiddealBind(){
try{
bind=newBind(tmpCmd);
if(bind.readbody()!=0){
unioncomLog.warn("ReadBinderror");
this.unErr=false;
}
bindResp=newBindResp(tmpCmd.getMsgHead());
bindResp.SetResult(0);
bindResp.write(output);
unioncomLog.debug("Bindsuccess!");
}catch(Exceptione){
unioncomLog.error("DelaUnionRecvBindError!"+
e.getMessage());
this.unErr=false;
}
}
privatevoiddealUnBind(){
try{
//unBind=(Unbind)tmpCmd;
unBindResp=newUnbindResp(tmpCmd.getMsgHead());
unBindResp.write(output);
unioncomLog.debug("UnBindsuccess!");
}catch(Exceptione){
unioncomLog.warn("Unbinderror!"+e.getMessage());
}
this.unErr=false;
}
privatevoidstartServices(){
booleanunStartServices=true;
while(unStartServices){
try{
serverSo=newServerSocket(ugInfo.getLocalServerPort(),5,
InetAddress.getByName(ugInfo.getLocalIpAdd()));
//serverSo.setSoTimeout(60000);
unStartServices=false;
unioncomLog.info("CreateunionrecvsocketOk!");
}catch(IOExceptione){
unioncomLog.warn("Createunionrecvsocketerror!"
+e.getMessage());
unStartServices=true;
UnioncomSubmit.thrSlp(3000);
}
}
}
privatevoidacceptConnection(){
//Accept失败
try{
so=serverSo.accept();
so.setSoTimeout(10000);
}catch(Exceptione){
unioncomLog.warn("AcceptError!"+e.getMessage());
this.closeServerSocket();
this.unAcceptErrorFlag=false;
this.unErr=false;
}
//Accept成功
try{
input=so.getInputStream();
output=so.getOutputStream();
}catch(IOExceptione){
unioncomLog.warn("GetI/OstreamError!"+e.getMessage());
this.closeService();
this.unAcceptErrorFlag=false;
this.unErr=false;
}
}
privatevoidcloseSocket(){
try{
so.close();
unioncomLog.info("SocketCloseSuccess!!!");
}catch(Exceptione){
unioncomLog.error("SocketCloseFailure!!!"+e.getMessage());
}
}
privatevoidcloseServerSocket(){
try{
serverSo.close();
unioncomLog.info("ServerSocketCloseSuccess!!!");
}catch(Exceptione){
unioncomLog
.error("ServerSocketCloseFailure!!!"+e.getMessage());
}
}
privatevoidcloseService(){
this.closeSocket();
this.closeServerSocket();
}
privatevoidinitServer(){
this.bind=null;
this.bindResp=null;
//this.unBind=null;
this.unBindResp=null;
this.tmpCmd=null;
this.cmd=null;
this.serverSo=null;
this.so=null;
this.output=null;
this.input=null;
this.unErr=true;
//this.closeSocketFlag=false;
unioncomLog.info("Memory***==="
+java.lang.Runtime.getRuntime().freeMemory());
}
(){
this.unInterrupt=false;
unioncomLog.info("Requreinterrupt!!!");
}
(intmsgCoding,byte[]msgContent){
StringdeliverContent=null;
try{
if(msgContent!=null){
if(msgCoding==8){//处理ucs32编码
deliverContent=newString(msgContent,
"UnicodeBigUnmarked");
}elseif(msgCoding==0){//处理ASCII编码
deliverContent=newString(msgContent,"ASCII");
}elseif(msgCoding==4){//处理binary编码
deliverContent=newString(msgContent);
}elseif(msgCoding==15){//处理GBK编码
deliverContent=newString(msgContent,"GBK");
//处理DELIVER数据包的短信息ID
}else{
unioncomLog.error("编码格式错误!");
return"";
}
}else
return"";
returndeliverContent;
}catch(){
unioncomLog.error("dealcontenterror!"+
ex.getMessage());
return"";
}
}
}
❸ java简答题 如何创建socket连接的过程
java socket建立连接的过程如下:
socket
1、 首先调用Socket类的构造函数,以服务器的指定的IP地址或指定的主机名和指定的端口号为参数,创建一个Socket流,在创建Socket流的过程中包含了向服务器请求建立通讯连接的过程实现。
2、 建立了客户端通讯Socket后。就可以使用Socket的方法getInputStream()和getOutputStream()来创建输入/输出流。这样,使用Socket类后,网络输入输出也转化为使用流对象的过程。
3、 使用输入输出流对象的相应方法读写字节流数据,因为流连接着通讯所用的Socket,Socket又是和服务器端建立连接的一个端点,因此数据将通过连接从服务器得到或发向服务器。这时我们就可以对字节流数据按客户端和服务器之间的协议进行处理,完成双方的通讯任务。
4、 待通讯任务完毕后,我们用流对象的close()方法来关闭用于网络通讯的输入输出流,在用Socket对象的close()方法来关闭Socket。
❹ 疯狂Java讲义:使用Socket进行通信[2]
程序清单 codes/ / /Client java
public class Client
{
public static void main(String[] args)
throws IOException
{
Socket socket = new Socket( )
//将Socket对应的输入流包装成BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(socket getInputStream()))
//进行普通IO操作
String line = br readLine()
System out println( 来自服务器的数据 + line)
//关闭输入流 socket
br close()
socket close()
}
}
上面程序中粗体字代码是使用ServerSocket和Socket建立网络连接的代码 斜体字代码是通过Socket获取输入流 输出流进行通信的代码 通过程序不难看出 一旦使用ServerSocket Socket建立网络连接之后 程序通过网络通信与普通IO并没有太大的区别
先运行上面程序中的Server类 将看到服务器一直处于等待状态 因为服务器使用了死循环来接受来自客户端的请求 再运行Client类 将可看到程序输出 来自服务器的数据 您好 您收到了服务器的新年祝福! 这表明客户端和服务器端通信成功
上面程序为了突出通过ServerSocket和Socket建立连接 并通过底层IO流进行通信的主题 程序没有进行异常处理 也没有使用finally块来关闭资源
实际应用中 程序可能不想让执行网络连接 读取服务器数据的进程一直阻塞 而是希望当网络连接 读取操作超过合理时间之后 系统自动认为该操作失败 这个合理时间就是超时时长 Socket对象提供了一个setSoTimeout(int timeout)来设置超时时长 如下的代码片段所示
Socket s = new Socket( )
//设置 秒之后即认为超时
s setSoTimeout( )
当我们为Socket对象指定了超时时长之后 如果在使用Socket进行读 写操作完成之前已经超出了该时间限制 那么这些方法就会抛出SocketTimeoutException异常 程序可以对该异常进行捕捉 并进行适当处理 如下代码所示
try
{
//使用Scanner来读取网络输入流中的数据
Scanner scan = new Scanner(s getInputStream())
//读取一行字符
String line = scan nextLine()
…
}
//捕捉SocketTimeoutException异常
catch(SocketTimeoutException ex)
{
//对异常进行处理
…
}
假设程序需要为Socket连接服务器时指定超时时长 即经过指定时间后 如果该Socket还未连接到远程服务器 则系统认为该Socket连接超时 但Socket的所有构造器里都没有提供指定超时时长的参数 所以程序应该先创建一个无连接的Socket 再调用Socket的connect()方法来连接远程服务器 而connect方法就可以接受一个超时时长参数 如下代码所示
//创建一个无连接的Socket
Socket s = new Socket()
//让该Socket连接到远程服务器 如果经过 秒还没有连接到 则认为连接超时
s connconnect(new InetAddress(host port) )
返回目录 疯狂Java讲义
编辑推荐
Java程序性能优化 让你的Java程序更快 更稳定
新手学Java 编程
Java程序设计培训视频教程
lishixin/Article/program/Java/hx/201311/27265
❺ java中用socket实现客户端与服务端双向连接问题
//服务端程序:
importjava.io.*;
importjava.net.*;
publicclassTCPServer{
publicstaticvoidmain(String[]args)throwsIOException{
newTCPServer().init();
}
@SuppressWarnings("static-access")
privatevoidinit()throwsIOException{
@SuppressWarnings("resource")
ServerSocketserver=newServerSocket(1000);
Socketclient=null;
while(true){
try{
client=server.accept();
BufferedInputStreambis=newBufferedInputStream(client.getInputStream());
byte[]b=newbyte[1024];
intlen=0;
Stringmessage="";
while((len=bis.read(b))!=-1){
message=newString(b,0,len);
System.out.print("客户端:"+client.getInetAddress().getLocalHost().getHostAddress()+"发来消息:"+message);
if("byte".equals(message.trim()))
client.close();
PrintWriterpw=newPrintWriter(client.getOutputStream(),true);
pw.println(message);
}
}catch(Exceptione){
System.err.println("客户端:"+client.getInetAddress().getLocalHost().getHostAddress()+"已断开连接!");
}
}
}
}
//客户端程序:
importjava.io.*;
importjava.net.Socket;
{
publicstaticvoidmain(String[]args)throwsIOException{
newTCPClient().init();
}
privatevoidinit()throwsIOException{
@SuppressWarnings("resource")
finalSocketclient=newSocket("127.0.0.1",1000);
BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));
Stringsend="";
while(true){
send=in.readLine();
PrintWriterout=newPrintWriter(client.getOutputStream(),true);
if(!"byte".equals(send.trim()))
out.println(send);
else{
out.println(send);
System.exit(0);
}
newThread(newTCPClient(){
@SuppressWarnings("static-access")
publicvoidrun(){
try{
BufferedInputStreambis=newBufferedInputStream(client.getInputStream());
byte[]b=newbyte[1024];
intlen=0;
while((len=bis.read(b))!=-1){
System.out.println("服务器:"+client.getInetAddress().getLocalHost().getHostAddress()+"发来消息:"+newString(b,0,len).trim());
}
}catch(IOExceptione){
System.err.println("连接服务器失败!");
}
}
}).start();
}
}
publicvoidrun(){}
}
//服务器测试结果:
客户端:192.168.0.200发来消息:001 byte
客户端:192.168.0.200发来消息:byte
客户端:192.168.0.200 已断开连接!
客户端:192.168.0.200发来消息:adasd
客户端:192.168.0.200 已断开连接!
//客户端测试结果:
---001号客户端--
001byte
服务器:192.168.0.200发来消息:001byte
byte //001礼貌说跟服务器说byte
---002号客户端--
adasd //002客户端直接关闭程序
服务器:192.168.0.200发来消息:adasd