Simple sending .txt file from one computer to another via TCP/IP

丶灬走出姿态 提交于 2019-12-02 11:06:10
Kickass

I'm assuming you are a new coder because I'm seeing a lot of inefficient code.

On the Client App: Don't redeclare the TcpClient, instead declare it in the global scope and just reuse it.

Then On the server side: Always use the correct datatype IF AT ALL possible

Int16 port = 8100;
//same as
int port = 8100;

Then on to the question: First you are only reading a single byte from the received data

int m=1;
byte[] b1 = new byte[m];
s.Read(b1, 0, b1.Length);
//Then if you know the length of the byte, why do the computation of b1.Length, just use
s.Read(b1, 0, 1);

I see now you are also opeing the connection on the Load event. But that variable is not in the global scope so you are essentially creating a variable in the Load event then after the Load event finishes, sending it to the garbage collection and then declaring a variable with the same name in the button click event.

So try declaring the TcpListener object in the global scope then assign it in the load event and start listening.

Now the AcceptTcpClient() method is a blocking method so it will block your thead until it receives a connection attempt at which point it will return the client object. So try to use this instead: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.accepttcpclient(v=vs.110).aspx

using System.Threading;
TcpClient client;
TcpListener server = new TcpListener("127.0.0.1",8100)
Thread incoming_connection = new Thread(ic);
incoming_connection.Start();

private void ic() {
client = server.AcceptTcpClient();
Stream s = client.GetStream();
//And then all the other code
}

Or you can use the Pending method as suggested by MSDN (on the ref page).

EDIT: using threading like this is 'not safe', so if you don't understand threading go read up on it first, this post doesn't cover how to use multi-threading.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!