Socket 通信问题
out=newPrintWriter(socket.getOutputStream(),true);利用它来发送信息.但是不调用out.close()不往外发送信息.调用...
out=new PrintWriter(socket.getOutputStream(),true);利用它来发送信息.但是不调用out.close()不往外发送信息.调用以后吧.socket closed.要实现循环通信和应答怎么办啊?现在这样发送一次就自己断开了.
展开
3个回答
展开全部
加一个循环while,我把我做过的一个代码贴出来,你可以看看有什么可用的不
package com.socket.server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server implements Runnable
{
public void run()
{
try
{
//创建ServerSocket
ServerSocket serverSocket = new ServerSocket(4567);
while (true)
{
//接受客户端请求
Socket client = serverSocket.accept();
System.out.println("accept");
try
{
//接收客户端消息
BufferedReader in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("read:" + str);
//向服务器发送消息
PrintWriter out = new PrintWriter( new BufferedWriter(
new OutputStreamWriter(client.getOutputStream())),true);
out.println("server message");
//关闭流
out.close();
in.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
finally
{
//关闭
client.close();
System.out.println("close");
}
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
//main函数,开启服务器
public static void main(String a[])
{
Thread desktopServerThread = new Thread(new Server());
desktopServerThread.start();
}
}
package com.socket.server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server implements Runnable
{
public void run()
{
try
{
//创建ServerSocket
ServerSocket serverSocket = new ServerSocket(4567);
while (true)
{
//接受客户端请求
Socket client = serverSocket.accept();
System.out.println("accept");
try
{
//接收客户端消息
BufferedReader in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("read:" + str);
//向服务器发送消息
PrintWriter out = new PrintWriter( new BufferedWriter(
new OutputStreamWriter(client.getOutputStream())),true);
out.println("server message");
//关闭流
out.close();
in.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
finally
{
//关闭
client.close();
System.out.println("close");
}
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
//main函数,开启服务器
public static void main(String a[])
{
Thread desktopServerThread = new Thread(new Server());
desktopServerThread.start();
}
}
展开全部
一般都是发一条消息就断开当前socket,下一次要连接的时候再重新new一个。
如果要你要的效果,用out.flush();就可以发送且不关闭socket。
不懂可以继续追问哈
如果要你要的效果,用out.flush();就可以发送且不关闭socket。
不懂可以继续追问哈
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
一楼正解 out.flush();
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询