我正在服务器和客户端之间实现简单的tcp聊天。我正在使用多线程,因此服务器和客户端可以同时发送和接收数据(全双工)。该程序有效,但如果服务器有一个控制台,既可以输入发送消息,也可以显示接收消息(客户端也是相同的情况),我无法编辑应该从服务器或客户端收到消息时发送给服务器或客户端的打字消息。另一边。例如:
运行(服务器控制台):
输入发送客户端的消息:
您:
客户:您好服务器
客户端:再见服务器。
对于此示例,我已经输入了要发送给客户端的消息,而客户端已经说过hi服务器再见服务器。在接收客户端之前,我看到了我输入的内容,但收到后,我看不到消息,也没有编辑它。
我只能使用控制台,因为我不熟悉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();
}
}
答案 0 :(得分:2)
有点晚了,但实际上我为我的编程课想出了这个聊天客户端的工作版本。我想我不妨在这里发布。我使用TCP(全双工)多线程,我让它在控制台工作。小问题是你看不到自己的名字(因为控制台只有一个活动行),但是它运行得很好。
服务器(客户端或多或少相同,显然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