gpt4 book ai didi

java 网络编程 TCP 聊天全双工

转载 作者:行者123 更新时间:2023-12-02 03:51:59 27 4
gpt4 key购买 nike

我正在服务器和客户端之间实现一个简单的 TCP 聊天。我使用多线程,以便服务器和客户端可以同时发送和接收数据(全双工)。该程序可以工作,但如果服务器有一个控制台,既可以键入发送消息,也可以显示接收消息(客户端的情况相同),则当从服务器接收到消息时,我无法编辑应发送到服务器或客户端的键入消息。对方。例如:

运行(服务器控制台):

输入消息发送给客户端:

你:

客户端:嗨服务器

客户端:服务器再见。

对于这个例子,我输入了一条消息发送给客户端,而客户端已经向服务器说“嗨,服务器再见”。在收到客户发来的消息之前,我可以看到我输入的内容,但收到后,我看不到消息也无法编辑它。

我只能使用控制台,因为我不擅长 GUI,并且我想要使用相同的控制台来发送和接收数据。

该程序的代码如下所示。

import java.net.*;
import java.io.*;
import java.util.Scanner;
public class ThreadServerSend implements Runnable {
String d;
Socket s1 = null;
Scanner sc = new Scanner(System.in);
public ThreadServerSend(Socket s)
{
s1=s;
}

public void run()
{
System.out.println("input msg to send client: ");
while (true){
try{

PrintStream p = new PrintStream(s1.getOutputStream());
System.out.println("you: ");

d=sc.nextLine();
p.println(d);
if (d.charAt(d.length()-1)=='.'){
s1.close();
break;}
}
catch(IOException e){}
}
}
}



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class ThreadServerReceive implements Runnable {

String m;
Socket s2 = null;
Scanner sc = new Scanner(System.in);
public ThreadServerReceive(Socket s)
{
s2=s;
}

public void run()
{
while (true){
try{

BufferedReader b = new BufferedReader(new InputStreamReader(s2.getInputStream()));
m = b.readLine();
System.out.println("client: "+m);

if (m.charAt(m.length()-1)=='.'){
s2.close();
break;}}
catch(IOException e){}
}
}
}




import java.io.*;
import java.net.*;
import java.util.*;
public class Server {

public static void main(String[] args) throws UnknownHostException, IOException{
// TODO Auto-generated method stub


ServerSocket s = new ServerSocket(444);

Socket s1 = s.accept();

new Thread(new ThreadServerSend(s1)).start();
ServerSocket s4 = new ServerSocket(443);
Socket s2=s4.accept();
new Thread(new ThreadServerReceive(s2)).start();



}
}



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ThreadClientSend implements Runnable {

String d;
Socket s1 = null;
Scanner sc = new Scanner(System.in);
public ThreadClientSend(Socket s)
{
s1=s;
}

public void run()
{
System.out.println("Input msg to send server: ");
while (true){
try{

PrintStream p = new PrintStream(s1.getOutputStream());

System.out.println("you: ");
String d = new Scanner(System.in).nextLine();



p.println(d);
if (d.charAt(d.length()-1)=='.'){
s1.close();
break;}
}
catch(IOException e){}
}
}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ThreadClientReceive implements Runnable {

String m;
Socket s1 = null;
Scanner sc = new Scanner(System.in);
public ThreadClientReceive (Socket s)
{
s1=s;
}

public void run()
{
while (true){
try{
BufferedReader b = new BufferedReader(new InputStreamReader(s1.getInputStream()));
m= b.readLine();
System.out.println("Server: "+m);
if (m.charAt(m.length()-1)=='.')
{
s1.close();
break;
}
}
catch(IOException e){}
}
}

}


import java.io.*;
import java.net.*;
import java.util.*;
public class Client {

public static void main(String[] args) throws UnknownHostException, IOException{
// TODO Auto-generated method stub


Socket s1= new Socket("localhost",444);
Socket s2 = new Socket("localhost",443);
new Thread(new ThreadClientReceive(s1)).start();

new Thread(new ThreadClientSend(s2)).start();




}

}

最佳答案

有点晚了,但我实际上为我的编程课想出了这个聊天客户端的工作版本。我想我不妨将其发布在这里。我使用 TCP(全双工)和多线程,并且让它在控制台中工作。一个小问题是你看不到自己的名字(因为控制台只有一个 Activity 行),但除此之外它工作得很好。

服务器(客户端或多或少相同,显然Sockets是普通套接字,而不是ServerSockets):

import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;


@SuppressWarnings("serial")
public class serverProgII extends Thread
{

private static ObjectOutputStream oos;
private static ObjectInputStream ois;
private static Socket connection;
private static ServerSocket server;
private static String ip, clientIP, textin, exitword ="exit";
private static networkmessage nmessage;
private static boolean connected = false;
private static boolean done = false;
private static String myName = "";
private static int counter = 0;

public static boolean started = false;
public String type;

public static void main(String[] args)
{
try {
BufferedReader brin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name:> "); //send prompt to DOS window
myName = brin.readLine(); //read in user input
setupConnection();
setupStreams();
started = true;
} catch (Exception e) {
System.out.println("Problem setting up streams and connection!");
}

serverProgII sender = new serverProgII("sender");
serverProgII receiver = new serverProgII("receiver");
sender.start();
receiver.start();
}

public serverProgII(String t)
{
super();
type = t;
}

public void run() {
while(started) {
switch(type) {
case "sender":
sender();
break;
case "receiver":
receiver();
break;
}
try {
Thread.sleep(500); //milliseconds
} catch(Exception e){}
}
}

/* runServer()
This is where all the actual work gets done.
*/

public void sender()
{
try {

BufferedReader inn = new BufferedReader(new InputStreamReader(System.in));
textin = inn.readLine();

sendData(textin);

if (textin.equals(exitword)) // if "exit" is typed in shutdown the server.
{
started = false;
serverShutdown();
}

}
catch (Exception e) {
e.printStackTrace();
}
}

public void receiver() {
try {
getData();
} catch(Exception e) {
System.out.println("Error getting data");
}
}


//setup connection
public static void setupConnection() throws IOException
{
System.out.println("SERVER MODE ACTIVATED");
server = new ServerSocket (8000); //create the socket at port 8000
System.out.println("Waiting For Connection...");
connection = server.accept(); //wait for a connection
System.out.println("Received connection: "+connection.getInetAddress());
clientIP=""+connection.getInetAddress(); //print out the client IP address

}//setupconnection()

//Setup streams connection
public static void setupStreams() throws IOException
{
//Open up Streams
System.out.println("Streams Setup");
oos=new ObjectOutputStream(connection.getOutputStream()); //construct object output stream
ois=new ObjectInputStream(connection.getInputStream());
oos.flush();

}//setupStreams()


//method to write/send network data
public void sendData(String toSend) throws IOException
{
try
{
nmessage = new networkmessage(myName, toSend);
oos.writeObject(nmessage);
}//try

catch (IOException ioException)
{
System.out.println("IO exception in sendData");
}

}//sendData()

//method to read in network data
public void getData() throws IOException
{
try
{
networkmessage messageIn =(networkmessage)(ois.readObject());
System.out.println(messageIn.ipnum +" << "+messageIn.text);

}//try

catch (Exception exp1)
{
System.out.println("IO exception in sendData");
}
}//getData()


public void serverShutdown()
{
System.out.println("exiting initiated");

try
{
done = true;
textin = "Chat is terminated. Have a nice day.";
oos.close();
server.close();
connection.close();
}

catch (Exception One)
{
System.out.println("bad termination");
}
}


} // class serverProg

关于java 网络编程 TCP 聊天全双工,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35795078/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com