java socket怎么写客户端向服务器发一堆话,服务器可以反馈发送的信息

OMRG OMRG 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
客户端
import java.io.*;
import java.net.*;
import java.util.Scanner;
class Receive implements Runnable
{
private Socket Read;
private DataInputStream input=null;
public Receive(Socket R) throws IOException
{
Read=R;
input=new DataInputStream(Read.getInputStream());
}
@Override
public void run()
{
String r;
try
{
while((r=input.readLine())!=null)
{
System.out.println(r);
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
Read.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public class Client
{
private Socket connection;
private PrintWriter output;
private DataInputStream input;
public void connect(InetAddress add) throws IOException
{
connection=new Socket(add,Server.port);
}
public void start() throws IOException
{
output=new PrintWriter(connection.getOutputStream());
input=new DataInputStream(connection.getInputStream());
Scanner s=new Scanner(System.in);
Receive receive=new Receive(connection);
Thread t=new Thread(receive);
t.start();
String send;
while(true)
{
send=s.nextLine();
output.write(send);
output.flush();
if(send.equals("end"))
break;
}
}
public static void main(String[] args) throws IOException
{
Client c=new Client();
c.connect(InetAddress.getLoopbackAddress());
c.start();
}
}

服务器
import java.io.*;
import java.net.*;
import java.util.ArrayList;
class ServerThread extends Thread
{
private Socket ThisSocket=null;
private PrintWriter output=null;
private DataInputStream input=null;
public ServerThread(Socket This) throws IOException
{
ThisSocket=This;
output=new PrintWriter(ThisSocket.getOutputStream());
input=new DataInputStream(ThisSocket.getInputStream());
}
public void run()
{
String recv;
try
{
while((recv=input.readLine())!=null)
{

System.out.println("客户端发来信息:"+recv);
output.write("服务器端已接受信息"+recv);
if(recv.equals("end"));
break;
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
input.close();
output.close();
Server.socketgroup.remove(ThisSocket);
ThisSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public class Server
{
private ServerSocket server;
public static ArrayList<Socket> socketgroup;
public static final int port=1920;
public Server() throws IOException
{
server=new ServerSocket(port);
socketgroup=new ArrayList<Socket>();
}
public void running() throws IOException
{
while(true)
{
Socket connection=server.accept();
socketgroup.add(connection);
new ServerThread(connection).start();
}
}
public static void main(String[] args) throws IOException
{
new Server().running();
}
}


错哪里。。一直Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.readLine(Unknown Source)
at ServerThread.run(Server.java:22)
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
OMRG
Java 51,407 成员 86,126 内容