Java以两种方式打开套接字流
我想做一个游戏(丛林速度),玩家点击图腾,它会改变屏幕上的位置(我用的是swing,这并不重要),关于本地化的信息应该发送给每个人 我想做一个服务器,获得玩家的点击,验证它,并发送更新信息给所有人。 在这个场景中,若有人点击了图腾,同时准备发送关于他自己点击的信息,客户机将监听服务器。 服务器侦听每个人,同时准备向所有人发送信息。 我尝试这样实现它: 服务器为每个玩家生成线程,监听内部的点击,并准备被中断以发送新的图腾本地化(我在ExecutorService上使用方法shutdownNow,这将导致线程中出现IOException,这将使它们停止循环并发送有关新本地化的信息),然后客户端获得它。 客户端也一样,若他点击,线程将被中断,它不会等待新的本地化,而是发送他的点击 问题是我不能创建流。下面是输出和代码 客户端:Java以两种方式打开套接字流,java,multithreading,sockets,Java,Multithreading,Sockets,我想做一个游戏(丛林速度),玩家点击图腾,它会改变屏幕上的位置(我用的是swing,这并不重要),关于本地化的信息应该发送给每个人 我想做一个服务器,获得玩家的点击,验证它,并发送更新信息给所有人。 在这个场景中,若有人点击了图腾,同时准备发送关于他自己点击的信息,客户机将监听服务器。 服务器侦听每个人,同时准备向所有人发送信息。 我尝试这样实现它: 服务器为每个玩家生成线程,监听内部的点击,并准备被中断以发送新的图腾本地化(我在ExecutorService上使用方法shutdownNow,这
2017-05-22T23:04:06.417Connected
2017-05-22T23:04:06.417Trying to make output
2017-05-22T23:04:06.417Trying to make input
服务器端:
2017-05-22T23:04:03.278Server Thread :Socket created
2017-05-22T23:04:03.294Server Thread :Waiting for client!
2017-05-22T23:04:06.385Server Thread :Correct, connected!
2017-05-22T23:04:12.239Trying to make input
客户端代码:
package client;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ServerConnection implements Runnable {
MainWindow frame;
Socket toServ;
Socket fromServ;
ServerSocket myServ;
ObjectOutputStream out;
ObjectInputStream reader;
public int x, y, totemx, totemy;
int i = 0;
public ServerConnection(MainWindow frame) {
try {
this.frame = frame;
myServ = new ServerSocket(1338);
toServ = new Socket("localhost", 1337);
fromServ = myServ.accept();
System.out.println(LocalDateTime.now() + "Connected");
try {
System.out.println(LocalDateTime.now() + "Trying to make output");
out = new ObjectOutputStream(new BufferedOutputStream(toServ.getOutputStream()));
} catch (IOException ex) {
Logger.getLogger(ServerConnection.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(LocalDateTime.now() + "Trying to make input");
reader = new ObjectInputStream(new BufferedInputStream(fromServ.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(ServerConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void run() {
System.out.println(LocalDateTime.now() + "Running");
while (true) {
try {
int xGot, yGot;
System.out.println(LocalDateTime.now() + "Waiting for params");
xGot = (int) reader.readInt();
yGot = (int) reader.readInt();
System.out.println(LocalDateTime.now() + "I got new params");
frame.refresh(xGot, yGot);
} catch (IOException ex) {
{
try {
System.out.println(LocalDateTime.now() + "Sending click thread: Sending my click");
out.writeInt(x);
out.writeInt(y);
System.out.println(LocalDateTime.now() + "Sent");
} catch (IOException ex1) {
Logger.getLogger(ServerConnection.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
}
}
}
服务器端代码
第一个文件:
package javaapplicationserwer;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Japko
*/
public class Server{
public int x, y;
ServerSocket serv = null;
ExecutorService executor;
Server()
{
x = 10;
y = 50;
executor = Executors.newFixedThreadPool(4);
try {
serv = new ServerSocket(1337);
System.out.println(LocalDateTime.now() + "Server Thread :Socket created");
while (true) {
System.out.println(LocalDateTime.now() + "Server Thread :Waiting for client!");
Socket fromSocket = serv.accept();
Socket toSocket=new Socket(fromSocket.getInetAddress(),1338);
System.out.println(LocalDateTime.now() + "Server Thread :Correct, connected!");
ClientConnection temp = new ClientConnection(fromSocket,toSocket, this);
executor.submit(temp);
}
} catch (IOException ex) {
Logger.getLogger(JavaApplicationSerwer.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void updateIt(int x, int y) {
System.out.println(LocalDateTime.now() + "Updating");
if (x == this.x && y == this.y) {
Random rand = new Random();
this.x = rand.nextInt(300);
this.y = rand.nextInt(300);
System.out.println(LocalDateTime.now() + "Updated");
executor.shutdownNow();
}
System.out.println(LocalDateTime.now() + "I notify");
}
}
第二个文件(实现runnable的类,由服务器为每个播放器创建):
听起来客户机有mate输出(这意味着服务器有输入),然后客户机想要创建输入,但服务器从构造函数中逃脱,甚至不尝试生成其输出
提前谢谢你的帮助 插座是两(2)路连接。客户端连接中只需要一个套接字
下面是一些执行简单tcp的代码:
package p;
import java.io.*;
import java.net.*;
import java.util.function.*;
public class Tcp {
static class Acceptor extends Thread {
Acceptor(ServerSocket serverSocket,Consumer<Socket> consumer) {
super("Acceptor");
this.serverSocket=serverSocket;
this.consumer=consumer;
}
@Override public void run() {
p("acceptor running on: "+serverSocket);
while(true)
try {
Socket socket=serverSocket.accept();
if(consumer!=null) consumer.accept(socket);
} catch(IOException e) {
p(getName()+" caught: "+e);
break;
}
}
final ServerSocket serverSocket;
final Consumer<Socket> consumer;
}
static class Connection implements Runnable {
Connection(Socket socket) throws IOException {
this.socket=socket;
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
out=new OutputStreamWriter(socket.getOutputStream());
}
boolean send(String string) {
try {
p("sending: "+string+" on: "+socket);
out.write(string+'\n'/*System.getProperty("line.separator")*/);
out.flush();
return true;
} catch(IOException e) {
e.printStackTrace();
}
return false;
}
void process(String string) {
p("connection on: "+socket+" received: "+string);
}
@Override public void run() {
p("connection on: "+socket+" is runing.");
String string=null;
try {
p("connection on: "+socket+" is trying to read.");
while((string=in.readLine())!=null) {
process(string);
}
} catch(IOException e) {
e.printStackTrace();
}
process(null);
p("connection on: "+socket+" is exiting run()");
}
final Socket socket;
final BufferedReader in;
final Writer out;
}
public static void p(String string) {
System.out.println(string);
}
Tcp(String host,Integer service) throws IOException {
ServerSocket serverSocket=new ServerSocket();
SocketAddress socketAddress=new InetSocketAddress(host,service);
serverSocket.bind(socketAddress);
Consumer<Socket> socketConsumer=(socket)-> {
p("accepted from: "+socket);
try {
final Connection connection=new Connection(socket) {
@Override void process(String string) {
super.process(string);
send(string.toUpperCase());
}
};
new Thread(connection,"incoming").start();
} catch(IOException e2) {
e2.printStackTrace();
}
};
new Acceptor(serverSocket,socketConsumer).start();
}
public static void main(String[] args) throws UnknownHostException,IOException,InterruptedException {
final String host="localhost";
final Integer service=1237;
Tcp tcp=new Tcp(host,service);
Socket socket=new Socket(host,service);
Connection c1=new Connection(socket);
new Thread(c1,"c1").start();
socket=new Socket(host,service);
Connection c2=new Connection(socket);
Thread.sleep(500);
new Thread(c2,"c2").start();
c1.send("foo");
c2.send("bar");
}
}
p包;
导入java.io.*;
导入java.net。*;
导入java.util.function.*;
公共类Tcp{
静态类接受程序扩展线程{
接受者(服务器套接字服务器套接字,使用者){
超级(“承兑人”);
this.serverSocket=serverSocket;
这个。消费者=消费者;
}
@重写公共无效运行(){
p(“在:+serverSocket上运行的接受器”);
while(true)
试一试{
Socket=serverSocket.accept();
如果(consumer!=null)consumer.accept(socket);
}捕获(IOE异常){
p(getName()+“捕获:”+e);
打破
}
}
最终服务器套接字服务器套接字;
最终消费者;
}
静态类连接实现可运行{
连接(套接字)引发IOException{
这个.socket=socket;
in=新的BufferedReader(新的InputStreamReader(socket.getInputStream());
out=新的OutputStreamWriter(socket.getOutputStream());
}
布尔发送(字符串){
试一试{
p(“发送:“+string+”开:“+socket”);
out.write(string+'\n'/*System.getProperty(“line.separator”)*/);
out.flush();
返回true;
}捕获(IOE异常){
e、 printStackTrace();
}
返回false;
}
作废处理(字符串){
p(“连接打开:“+socket+”接收:“+string”);
}
@重写公共无效运行(){
p(“连接打开:“+socket+”正在运行”);
String=null;
试一试{
p(“连接打开:“+socket+”正在尝试读取。”);
而((string=in.readLine())!=null){
进程(字符串);
}
}捕获(IOE异常){
e、 printStackTrace();
}
进程(空);
p(“连接打开:“+socket+”正在退出run()”;
}
最终插座;
最终缓冲读取器输入;
最终作者出来了;
}
公共静态void p(字符串){
System.out.println(字符串);
}
Tcp(字符串主机,整数服务)引发IOException{
ServerSocket ServerSocket=新的ServerSocket();
SocketAddress SocketAddress=新的InetSocketAddress(主机、服务);
绑定(socketAddress);
消费者插座消费者=(插座)->{
p(“接受自:“+插座”);
试一试{
最终连接=新连接(插座){
@重写无效进程(字符串){
超级进程(字符串);
send(string.toUpperCase());
}
};
新线程(连接,“传入”).start();
}捕获(IOE2异常){
e2.printStackTrace();
}
};
新的接受器(serverSocket,socketConsumer).start();
}
公共静态void main(字符串[]args)抛出UnknownHostException、IOException、InterruptedException{
最后一个字符串host=“localhost”;
最终整数服务=1237;
Tcp=新的Tcp(主机、服务);
套接字=新的套接字(主机、服务);
连接c1=新连接(插座);
新螺纹(c1,“c1”).start();
套接字=新套接字(主机、服务);
连接c2=新连接(插座);
睡眠(500);
新螺纹(c2,“c2”).start();
c1.发送(“foo”);
c2.发送(“bar”);
}
}
out.flush()在本例中有帮助 您是否尝试过在写入调用之后添加out.flush()
?另外,println调试显示的内容是什么?“无法创建流”不是问题描述,“从构造函数中转义”也不是问题描述。@Gray out.flush()有帮助。谢谢,因为我读到了,我当时不能有输入和输出流。我错了吗?我有一个只有一个插座的版本,但仍然无法工作。@JakubJabłoński,你在哪里读到的?你到底在哪里读到这些垃圾?
package p;
import java.io.*;
import java.net.*;
import java.util.function.*;
public class Tcp {
static class Acceptor extends Thread {
Acceptor(ServerSocket serverSocket,Consumer<Socket> consumer) {
super("Acceptor");
this.serverSocket=serverSocket;
this.consumer=consumer;
}
@Override public void run() {
p("acceptor running on: "+serverSocket);
while(true)
try {
Socket socket=serverSocket.accept();
if(consumer!=null) consumer.accept(socket);
} catch(IOException e) {
p(getName()+" caught: "+e);
break;
}
}
final ServerSocket serverSocket;
final Consumer<Socket> consumer;
}
static class Connection implements Runnable {
Connection(Socket socket) throws IOException {
this.socket=socket;
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
out=new OutputStreamWriter(socket.getOutputStream());
}
boolean send(String string) {
try {
p("sending: "+string+" on: "+socket);
out.write(string+'\n'/*System.getProperty("line.separator")*/);
out.flush();
return true;
} catch(IOException e) {
e.printStackTrace();
}
return false;
}
void process(String string) {
p("connection on: "+socket+" received: "+string);
}
@Override public void run() {
p("connection on: "+socket+" is runing.");
String string=null;
try {
p("connection on: "+socket+" is trying to read.");
while((string=in.readLine())!=null) {
process(string);
}
} catch(IOException e) {
e.printStackTrace();
}
process(null);
p("connection on: "+socket+" is exiting run()");
}
final Socket socket;
final BufferedReader in;
final Writer out;
}
public static void p(String string) {
System.out.println(string);
}
Tcp(String host,Integer service) throws IOException {
ServerSocket serverSocket=new ServerSocket();
SocketAddress socketAddress=new InetSocketAddress(host,service);
serverSocket.bind(socketAddress);
Consumer<Socket> socketConsumer=(socket)-> {
p("accepted from: "+socket);
try {
final Connection connection=new Connection(socket) {
@Override void process(String string) {
super.process(string);
send(string.toUpperCase());
}
};
new Thread(connection,"incoming").start();
} catch(IOException e2) {
e2.printStackTrace();
}
};
new Acceptor(serverSocket,socketConsumer).start();
}
public static void main(String[] args) throws UnknownHostException,IOException,InterruptedException {
final String host="localhost";
final Integer service=1237;
Tcp tcp=new Tcp(host,service);
Socket socket=new Socket(host,service);
Connection c1=new Connection(socket);
new Thread(c1,"c1").start();
socket=new Socket(host,service);
Connection c2=new Connection(socket);
Thread.sleep(500);
new Thread(c2,"c2").start();
c1.send("foo");
c2.send("bar");
}
}